By default Django admin site shows all records of a related model/table for viewing. How can I show only the records that meet certain criteria?
Asked
Active
Viewed 1.1k times
17
-
Do you mean by default, or do you just want that option to be available from the changelist page? – Dominic Rodger Feb 17 '10 at 09:05
-
By default. Whenever I load the page, it shows only records that mean some requirements. Those requirements can be changed in the back-end. – Viet Feb 17 '10 at 09:07
-
And also, how to make those to show up in the changelist page? – Viet Feb 17 '10 at 09:08
2 Answers
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.

Dominic Rodger
- 97,747
- 36
- 197
- 212

Will Hardy
- 14,588
- 5
- 44
- 43
-
1
-
But in this way, it's not possible to get additional queries for other users if you'd want to search for that. So it doesn't answer the question the way I read it. – odinho - Velmont Sep 16 '11 at 15:28
-
22
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)

streetlogics
- 4,640
- 33
- 33
-
See what happened there! His answer was good..... yours was better. Sterling work. – A H Bensiali Oct 13 '17 at 00:01
-