Home > Mobile >  Overriding django admin get_queryset()
Overriding django admin get_queryset()

Time:01-20

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

CodePudding user response:

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

CodePudding user response:

If you want ProxyCategoryAdmin to return both languages, do this:

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

    def get_queryset(self, request):
        qs = super().get_queryset(request)
        return qs.filter(language_in=['zh','en'])

When you inherit the CategoryAdmin, you end up with 2 filters: EN and ZH instead of EN or ZH

  • Related