Search code examples
djangodjango-admin

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.


Solution

  • 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')