Make a one-to-many relationship in django

I am trying to make a one-to-many relationship in django.

In my model, I have a Person class and a group of classes, and the relation I want to do is that one group can have N people inside, and the group cannot exist without at least one person inside

In a MER diagram, it will look like (imagine these are entities and relationships)

| group | 1 ==== <> ----- H | person |

+4
source share
1 answer

According to Arthur, this is well documented in the Django documentation.

This is actually pretty simple:

from django.db import models class Person(models.Model): # Some other fields group = models.ForeignKey(Group, related_name='people') class Group(models.Model): # Some fields 

As you can see, you simply create the foreign key in the person → class, which is pretty much the same as how you manually configured it in the database, if you do.

Django will automatically add an inverse relationship so you can find people from the group:

 some_group.people 

Note that related_name indicates the name of the inverse relationship. This is optional, but I think you want to use people instead of persons .

+16
source

All Articles