You need select_related or prefetch_related
A database query for each object in Django
-
01-06-2022 - |
سؤال
I have a model Photos with a ForeignKey to the model User.
If I print a photo objects fields in a template, e.g.
<img src="{{ object.image.url }}" alt="{{ object.caption }}">
there will be 1 query, but if I print information about the user, e.g.
{{ object.caption }} by {{ object.user.first_name }}
there will be 2 queries. So in a ListView with 40 objects, there will be more than 40 queries to get the informations about the user. Is this right? To me it seems stupid, but I don't know if it is possible to get the same stuff done while avoiding so many database queries.
المحلول
لا تنتمي إلى StackOverflow