Many-to-One Relationships
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)
# 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")
Last updated