Override default queryset in Django admin

前端 未结 6 2072
孤城傲影
孤城傲影 2020-11-27 14:51

One of my models has a deleted flag, which is used to hide objects globally:

class NondeletedManager(models.Manager):
    \"\"\"Returns only objects which ha         


        
6条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-27 15:17

    You can do this with a Django proxy model.

    # models.py
    class UnfilteredConversation(Conversation):
        class Meta:
            proxy = True
    
        # this will be the 'default manager' used in the Admin, and elsewhere
        objects = models.Manager() 
    
    # admin.py
    @admin.register(UnfilteredConversation)
    class UnfilteredConversationAdmin(Conversation):
        # regular ModelAdmin stuff here
        ...
    

    Or, if you have an existing ModelAdmin class you want to re-use:

    admin.site.register(UnfilteredConversation, ConversationAdmin)
    

    This approach avoids issues that can arise with overriding the default manager on the original Conversation model - because the default manager is also used in ManyToMany relationships and reverse ForeignKey relationships.

提交回复
热议问题