In a one-to-many relationship
, each record in one model can be associated with multiple records in another model.
In django, the one-to-many
relationship can be achieved using the Foreign Key
.
Lets create a new model for the demo of one-to-many
relationship.
class Post(models.Model):
author = models.ForeignKey(Person, on_delete=models.CASCADE)
title = models.CharField(max_length=100)
content = models.TextField()
After adding this model, you need to run the python manage.py makemigrations
and python manage.py migrate
command.
python manage.py makemigrations
python manage.py migrate
Instance for the model can be created as follows :
from modeldemo.models import *
person = Person.objects.get(id=1)
post1 = Post.objects.create(author=person, title='Post 1', content='Post 1 Content')
post2 = Post.objects.create(author=person, title='Post 2', content='Post 2 Content')
In this example, we have a one-to-many relationship between the Person
model and the Post
model, where each person can author multiple posts, but each post is associated with only one author.
You can view all posts associated with a person as follows :
person.post_set.all()