make a One to Many Relation in django

六月ゝ 毕业季﹏ 提交于 2019-12-04 11:55:01

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.

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