I have models like these:
class Comment(models.Model):
text = models.TextField(max_length = 250, blank = False)
author = models.ForeignKey(User)
content_type = models.ForeignKey(ContentType)
object_id = models.PositiveIntegerField()
content_object = generic.GenericForeignKey('content_type', 'object_id')
class Product(models.Model):
name = models.CharField(max_length = 40)
comments = generic.GenericRelation(Comment)
In this template I show the latest 5 comments of all products:
<ul>
{% for comment in last_comments %}
<li><a href="/user/{{ comment.author }}/">{{ comment.author }}</a> on <a href="/product/{{ comment.content_object.name }}/">{{ comment.content_object }}</a>
<br>{{ comment.text }}</li>
{% endfor %}
</ul>
If I get last_comments
with last_comments = Comment.objects.all().order_by('-id')[:5]
django debug toolbar says was performed 25 queries.
If I get last_comments
with last_comments = Comment.objects.select_related().all().order_by('-id')[:5]
django debug toolbar says was performed 20 queries.
But why select_related
doesn't select the related content_object also? In django debug toolbar I see 5 queries for getting the product. And are certainly the consequence of {{ comment.content_object }}
Probably the reason is because I use GenericForeignKey in Comment
model.
Have you ideas about it?