2๐
โ
If you want to get all comments on a post with a single query then it would be good to have every comment link to the asssociated post. You can use a separate link to indicate the parent comment.
Basically:
class Post(models.Model):
...
comments = models.ManyToManyField('Comment')
# link to all comments, even children of comments
class Comment(models.Model):
...
child_comments = models.ManyToManyField('Comment')
# You may find it easier to organise these into a tree
# if you use a parent_comment ForeignKey. That way the
# top level comments have no parent and can be easily spotted.
Post.objects.all().select_related('comments').get(pk=1)
The many to many in this takes a little extra work to create the association, as it uses an intermediate table. If you want a pure one to many then you need a ForeignKey
on the Comment
but then you are restricted to a prefetch_related
instead of a select_related
, which then involves an extra database hit.
This is also better in that you do not have an untyped foreign key reference (your PostitiveIntegerField
).
You then need to arrange the comments into a tree structure, but that is outside the scope of your question.
๐คMatthew Franglen
Source:stackexchange.com