Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to limit queryset/the records to view in Django admin site?

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?

like image 423
Viet Avatar asked Feb 17 '10 08:02

Viet


People also ask

How do I restrict access to parts of Django admin?

Django admin allows access to users marked as is_staff=True . To disable a user from being able to access the admin, you should set is_staff=False . This holds true even if the user is a superuser. is_superuser=True .

What is List_filter in Django?

For Django 1.4-1.7, list_filter allows you to use a subclass of SimpleListFilter . It should be possible to create a simple list filter that lists the values you want.

What we can do in admin portal in Django?

Overview. The Django admin application can use your models to automatically build a site area that you can use to create, view, update, and delete records. This can save you a lot of time during development, making it very easy to test your models and get a feel for whether you have the right data.


2 Answers

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.

like image 167
Will Hardy Avatar answered Sep 21 '22 17:09

Will Hardy


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)
like image 28
streetlogics Avatar answered Sep 20 '22 17:09

streetlogics