开发者

Django admin changelist - restrict where field is NULL

开发者 https://www.devze.com 2022-12-16 20:32 出处:网络
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.

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.


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


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.


I've decided to use limited queryset manager as objects. For ModelAdmin I've copied queryset() from django/contrib/admin/options.py and changed _default_manager by mine unlimited queryset manager. Simple!

0

精彩评论

暂无评论...
验证码 换一张
取 消