0
0
Djangoframework~30 mins

ForeignKey for one-to-many in Django - Mini Project: Build & Apply

Choose your learning style9 modes available
ForeignKey for one-to-many
📖 Scenario: You are building a simple blog application where each blog post can have many comments. You want to connect comments to their blog posts using Django's ForeignKey to show this one-to-many relationship.
🎯 Goal: Create two Django models: Post and Comment. Use a ForeignKey in Comment to link each comment to a single post. This will let you store multiple comments for each post.
📋 What You'll Learn
Create a Post model with a title field
Create a Comment model with a text field
Add a ForeignKey in Comment to Post with on_delete=models.CASCADE
Use related_name='comments' in the ForeignKey for easy access from Post
Follow Django model syntax and conventions
💡 Why This Matters
🌍 Real World
Blogs, forums, and social media apps often use one-to-many relationships to connect posts with comments or replies.
💼 Career
Understanding ForeignKey relationships is essential for backend developers working with Django to build relational data models.
Progress0 / 4 steps
1
Create the Post model
Create a Django model called Post with a single field title that is a CharField with max length 100.
Django
Need a hint?

Use models.CharField(max_length=100) for the title field inside the Post model.

2
Create the Comment model
Create a Django model called Comment with a single field text that is a TextField.
Django
Need a hint?

Use models.TextField() for the text field inside the Comment model.

3
Add ForeignKey to Comment
Add a ForeignKey field called post to the Comment model. It should link to the Post model, use on_delete=models.CASCADE, and have related_name='comments'.
Django
Need a hint?

Use models.ForeignKey(Post, on_delete=models.CASCADE, related_name='comments') for the post field.

4
Add __str__ methods for readability
Add a __str__ method to both Post and Comment models. For Post, return the title. For Comment, return the first 20 characters of text.
Django
Need a hint?

Define __str__ methods to return self.title for Post and self.text[:20] for Comment.