0

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.

Alasdair
  • 298,606
  • 55
  • 578
  • 516
Jamgreen
  • 10,329
  • 29
  • 113
  • 224

1 Answers1

4

You need select_related or prefetch_related

Aamir Rind
  • 38,793
  • 23
  • 126
  • 164