Home > Software engineering >  How to work many to one relationship in django
How to work many to one relationship in django

Time:04-21

Hello friends I am trying to figure out how to work properly with a One to Many relationship.

I want to create two models, The first model is Post And a second model is Comment

Now I say that every post has many comments, and every comment has one post.

class Post(models.Model):
  user = models.ForeignKey(User, on_delete=models.CASCADE)
  title = models.CharField(max_length=50)
  message = models.TextField(max_length=256,null=True)
  
  def __str__(self):
    return str(self.title)

class Comment(models.Model):
  user = models.ForeignKey(User, on_delete=models.CASCADE)
  post = models.ForeignKey(Post, on_delete=models.CASCADE)
  message = models.TextField(max_length=256, null=True)

I'm trying to figure out how I can get all the posts and all the comments so that all the comments match the post to which they belong That is, in the functions in the views file how do I send back this option.

because on the HTML page I want to display the post with all its comments but there are a number of posts, so how do I do that?

The only thought I can do is this:

 dict = {}
 all_posts = Post.objects.all()
    for post in all_posts:
      dict[post] = Comment.objects.filter(post=post).values()
    print(dict)

but I have a feeling there is something better

CodePudding user response:

You can access all related comments for a post by using post.comment_set.all() see Following relationships “backward”

{% for post in all_posts %}
    {{ post }}
    {% for comment in post.comment_set.all %}
        {{ comment }}
    {% endfor %}
{% endfor %}

To reduce the number of queries use prefetch_related to get all related comments for all posts in a single query

def posts_list(request):
    all_posts = Post.objects.prefetch_related('comment_set')
    return render(request, 'template.html', {'all_posts': all_posts})
  • Related