Get comments of Post (one to many relation)
-
26-12-2019 - |
سؤال
One to many relationship.
I want to get the comment of the post where both are in the same table named post, but the comments has data on a parent
column (parent post)
I am from PHP and using laravel i would just $this->hasMany('post','parent');
But in django how do I do this?
To return all the comments of that post. must show the post and have an attribute comments, and show the comments there.
المحلول
as you can read here: https://docs.djangoproject.com/en/dev/ref/models/relations/
A “related manager” is a manager used in a one-to-many or many-to-many related context. This happens in two cases:
The “other side” of a ForeignKey relation. That is:
from django.db import models
class Reporter(models.Model):
# ...
pass
class Article(models.Model):
reporter = models.ForeignKey(Reporter)
In the above example, the methods below will be available on the manager reporter.article_set
.
In your case is post.post_set
. If you don't like post_set
you can specify the related_name
in the ForeignKey:
parent = models.ForeignKey(Post, related_name='comments')
At this point you can query: post.comments