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.
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.
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.
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')
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With