Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Avoid 1+n queries in Django admin list view

I have a Django model:

class Book(models.Model):
    author = models.ForeignKey(Author, on_delete=models.PROTECT)

    @property
    def slug(self):
        return slugify(self.author.name)

Now if I add slug field to admin list_display, there will be a separated query for each instance.

How to make just one query for all instances?

I tried to use select_related in the ModelAdmin class, but I did not get it working.

like image 941
Eerik Sven Puudist Avatar asked Oct 27 '19 18:10

Eerik Sven Puudist


People also ask

How to fix n 1 Problem in django?

Tools to Fix the N+1 Queries Problem. Django provides two QuerySet methods that can turn the N queries back into one query, solving the performance issue. These methods are select_related() (docs) and prefetch_related() (docs). They work similarly - both fetch the related model alongside the original query.

How do I show all columns in Django admin?

To display both the three columns in the admin site model list page, you need edit the Django app's admin.py file ( dept_emp / admin.py ), then define a class which extends django. contrib. admin. ModelAdmin class.


1 Answers

You can override get_queryset() of your ModelAdmin to add your select_related.


    def get_queryset(self, request):
        return super().get_queryset(request).select_related('author')
like image 132
jpm Avatar answered Sep 21 '22 13:09

jpm