Many-to-One Relationships
Create the Post
and Comment
models:
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:
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