[Fixed]-How to limit queryset/the records to view in Django admin site?

33👍

In your admin definition, you can define a queryset() method that returns the queryset for that model’s admin. eg:

class MyModelAdmin(admin.ModelAdmin):
    def queryset(self, request):
        qs = super(MyModelAdmin, self).queryset(request)
        return qs.filter(user=request.user)

Then only objects with user=request.user will be visible in the admin.

10👍

I know this has an “accepted answer”, but I just wanted to throw this out there since I came across this answer while pursuing something else and realized I had an alternative solution that I found and use often that gives me more granular level control than the accepted answer.

class TestAdmin(admin.ModelAdmin):
    def formfield_for_foreignkey(self, db_field, request, **kwargs):
        if db_field.name == "FIELD":
            kwargs["queryset"] = TestModel.objects.filter(test=False)
        return super(TestAdmin, self).formfield_for_foreignkey(db_field, request, **kwargs)

    def formfield_for_manytomany(self, db_field, request, **kwargs):
        if db_field.name == "FIELDS":
            kwargs["queryset"] = TestModel.objects.filter(test=False)
        return super(TestAdmin, self).formfield_for_manytomany(db_field, request, **kwargs)

Leave a comment