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 fieldCreate a
Comment model with a text fieldAdd a
ForeignKey in Comment to Post with on_delete=models.CASCADEUse
related_name='comments' in the ForeignKey for easy access from PostFollow 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