views:

151

answers:

2

I'm setting up a new Django app and need to customize the Admin for a given table by restricting the records where a field is NULL. Basically a built-in, permanent filter.

Seems like changelist_view needs to be overridden, but I'm uncertain what that change would look like.

There's no code to be included as I'm not overriding changelist_view right now.

+1  A: 

You can override default manager, but it has a drawback that you'll have to explicitly specify original manager in all your queries:

class MyManager(models.Manager):
    def get_query_set(self):
        return super(MyManager, self).get_query_set().filter(my_field__isnull=False)

class MyModel(models.Model):
   objects = MyManager()
   all_objects = models.Manager()

MyModel.all_objects.all()    # all objects including those having my_field=None
Antony Hatchkins
Thanks Antony. This example applies to ALL objects, correct? MyManager and MyModel would retrict all queries with that filter?
jro
django admin uses the manager tied to `.objects`. You can use whichever manager you like (either `objects` or `all_objects`). In certain cases (like "reverse" lookup) `objects` is used automatically in your queries, so if you use this model in your code often, search another solution. This one is more like a quickfix.
Antony Hatchkins
Thanks Antony. Going to write my own admin page instead.
jro
Welcome. Drop a line here if you come up with an elegant solution
Antony Hatchkins
+1  A: 

There's not really a good way to do this at present - there is in fact an open ticket on Django requesting the ability to customise what QuerySet gets used for the admin views - see ticket #10761. Antony's solution will work in the short term, but you may have to wait until that ticket is resolved for a proper solution.

Dominic Rodger
Thanks Dominic.
jro