Reputation: 6047
Rendering a page gets really slow when related objects are requested in a template.
class Item(models.Model):
name = models.CharField(max_length=160)
...
class Box(models.Model):
...
items = models.ForeignKey(Item, on_delete=models.CASCADE, null=True)
#template
{% for item in items %}
{{ item.box_set.first }}
{{ item.box_set.latest }}
{% endfor %}
Debug toolbar shows there many duplicate queries. Why is this happening? Is there a way to speed this up?
Upvotes: 0
Views: 26
Reputation: 13731
The Django ORM has to make a request to the database when accessing a related field unless it's already cached. The main ways of caching the related objects are via select_related
and prefetch_related
.
What you're trying to do is a bit more difficult; you're trying to get two specific items from a collection. You can use .annotate()
and Subquery
to pull singular fields from a related model. This would be useful if you just wanted to display single field from box, but if you need the whole box instance this won't work.
Upvotes: 1