在Django建立一对多关系 [英] make a One to Many Relation in django

查看:155
本文介绍了在Django建立一对多关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正试图在Django中建立一对多的关系.

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

在我的模型中,我有一个Person类和一个Group类,我想建立的关系是一个Group内部可以有N个人,而如果没有至少一个内部的人,这个组就不可能存在

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

在MER图中,就像(假设这些是实体和关系)

In a MER diagram it would be like(imagine these are entities and relations)

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

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

推荐答案

正如Arthur所说,这在Django文档中已有很好的记录.

As Arthur states, this is documented quite well in the Django documentation.

实际上很容易:

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

如您所见,您只需在person类中创建一个外键->这与您应该在数据库中手动设置它的方式相当.

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将自动添加反向关系,以便您可以从组中找到人:

Django will automatically add the reverse relation, such that you can find people from a group:

some_group.people

请注意,related_name指定反向关系的名称.这是可选的,但我想您想使用people而不是persons.

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.

这篇关于在Django建立一对多关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆