Reputation: 1506
Well, I believe this is a general question.
Let's say I have a model, called Book, and another model called Author. And Author is the foreign key of Book.
Easy, ha?
On BookAdmin page, I want to show Author of Book. So In the list_display field I have:
list_display = ('book_name', 'author'.....)
Then I use django-debug-toolbar to check the number of queries executed when loading the page. There are about 100+ queries have been executed. (I have 100 book entries on same page)
If I don't include 'author', there are only 5 queries (something like that).
I know that the extra queries come from foreign key.
My question is that is there anyway to reduce the number of queries being executed when we are dealing with foreign key?
I don't want to perform any complicate operation. I just want the call the unicode() method in that foreign key model.
Thanks in advance
Upvotes: 0
Views: 186
Reputation: 1506
Well, I found it out myself.
The way to do it is to override the queryset() in BookAdmin class.
Like:
def queryset(self, request):
return Book.objects.all().select_related('author')
That is it. Django will load the Author in the same time it loads Book. So there will be only on database hit rather than over 100 hits.
Upvotes: 1