Many-to-One Relationships

Create the Post and Comment models:


from django.db import models

class Post(models.Model):
    title = models.CharField(max_length=100)
    content = models.TextField()

class Comment(models.Model):
    post = models.ForeignKey(Post, on_delete=models.CASCADE)
    text = models.TextField()
    date_created = models.DateTimeField(auto_now_add=True)

In this example:

We have two models: Post and Comment. Each Post can have multiple Comment objects associated with it, creating a Many-to-One relationship. The Comment model has a foreign key field post that establishes the relationship to the Post model. The on_delete=models.CASCADE argument means that if a Post is deleted, all its associated comments will be deleted as well. We also have a text field to store the content of the comment and a date_created field to store the creation date.

Create and retrieve Post and Comment objects:

# Create a new post
post = Post.objects.create(title="Sample Post", content="This is the content of the post.")

# Create comments related to the post
comment1 = Comment.objects.create(post=post, text="First comment on the post.")
comment2 = Comment.objects.create(post=post, text="Second comment on the post.")

# Retrieve comments for a specific post
comments_for_post = Comment.objects.filter(post=post)

# Access the related post for a comment
for comment in comments_for_post:
    print(f"Comment: {comment.text}")
    print(f"Posted on: {comment.date_created}")
    print(f"Related Post: {comment.post.title}\n")

We first create a Post and two related Comment objects. Each comment is associated with the post it relates to. We then retrieve all comments related to a specific post using Comment.objects.filter(post=post). To access the related Post for each comment, we use the comment.post attribute, which gives us access to the associated Post object. This example demonstrates a Many-to-One relationship in Django between the Post and Comment models. It allows you to associate multiple comments with a single post and easily access them through the foreign key relationship.

Last updated