Search code examples
pythondjangodjango-modelsinheritancedjango-admin

Overriding django admin get_queryset()


I have two models which is one of them proxy model. In admin I registered both and overrided get_queryset() method but it is not working as expected.
admin.py

@admin.register(Category)
class CategoryAdmin(admin.ModelAdmin):

    def get_queryset(self, request):
        qs = super().get_queryset(request)
        return qs.filter(language='en')

@admin.register(ProxyCategory)
class ProxyCategoryAdmin(CategoryAdmin):

    def get_queryset(self, request):
        qs = super().get_queryset(request)
        return qs.filter(language='zh')

In admin page ProxyCateegoryAdmin not showing objects, if I remove get_queryset() from CategoryAdmin, it works but wanted filter both of them. Thanks in advance


Solution

  • You can use self.model in the get_queryset method to filter the correct model.

    @admin.register(Category)
    class CategoryAdmin(admin.ModelAdmin):
    
        def get_queryset(self, request):
            qs = super().get_queryset(request)
            if self.model == Category:
                return qs.filter(language='en')
            return qs
    
    @admin.register(ProxyCategory)
    class ProxyCategoryAdmin(CategoryAdmin):
        pass