Efficient query with Generic Relations
These are my models:
class Comment(models.Model):
content_type = models.ForeignKey(ContentType)
object_id = models.PositiveIntegerField(_('object ID'))
content_object = generic.GenericForeignKey()
user = models.ForeignKey(User)
comment = models.TextField(_('comment'))
class Post(models.Model):
title = models.CharField(_('name'), max_length=80)
creator = models.ForeignKey(User, related_name="created_posts")
created = models.DateTimeField(_('created'), default=datetime.now)
body = models.TextField(_('body'), null=True,开发者_如何转开发 blank=True)
Now in my views.py I get a post with this istruction:
post = get_object_or_404(Post, id=id)
At this point in my views.py, what is the most efficient query ( with ORM ) to get all comments of that post ?
You should define comments = generic.GenericRelation(Comment)
on the Post, to give you easy access from Post to Comment. Once you've done that, it's a simple backwards relationship:
comments = post.comments.all()
Note that this isn't really a question of efficiency. Getting all the related items via a backwards generic relationship will always incur at most two queries - one to get the relevant ContentType, which is automatically cached on first look-up, and once to get the actual items.
If you had asked how to get all the comments for multiple posts as efficiently as possible, I'd point you to my blog for a good technique, but since you haven't I won't because that would just be blog-whoring.
精彩评论