问题
I am trying to make a one-to-many relation in django.
In my model I have a class Person and a class Group and the relation I want to make is that one Group can have N people inside, and a group cann't exist without at least one person inside
In a MER diagram it would be like(imagine these are entities and relations)
|group|1====<>-----N|person|
回答1:
As Arthur states, this is documented quite well in the Django documentation.
It is in fact quite easy:
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 a foreign key in the person class -> this is quite equivalent to how you would set it up manually in the database, if you should do so.
Django will automatically add the reverse relation, such that you can find people from a group:
some_group.people
Note that the related_name
specifies the name of the reverse relation. This is optional, but I guess you want to use people
instead of persons
.
来源:https://stackoverflow.com/questions/13997562/make-a-one-to-many-relation-in-django