make a One to Many Relation in django

拜拜、爱过 提交于 2019-12-09 20:46:54

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!