如何在 Django 中表达一对多关系? [英] How to express a One-To-Many relationship in Django?

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

问题描述

我现在正在定义我的 Django 模型,但我意识到模型字段类型中没有 OneToManyField.我确定有办法做到这一点,所以我不确定我错过了什么.我基本上有这样的事情:

I'm defining my Django models right now and I realized that there wasn't a OneToManyField in the model field types. I'm sure there's a way to do this, so I'm not sure what I'm missing. I essentially have something like this:

class Dude(models.Model):
    numbers = models.OneToManyField('PhoneNumber')

class PhoneNumber(models.Model):
    number = models.CharField()

在这种情况下,每个Dude可以有多个PhoneNumber,但关系应该是单向的,因为我不需要从中知道Dude 拥有它的 PhoneNumber 本身,因为我可能有许多不同的对象拥有 PhoneNumber 实例,例如 Business例如:

In this case, each Dude can have multiple PhoneNumbers, but the relationship should be unidirectional, in that I don't need to know from the PhoneNumber which Dude owns it, per se, as I might have many different objects that own PhoneNumber instances, such as a Business for example:

class Business(models.Model):
    numbers = models.OneToManyField('PhoneNumber')

我将用什么替换模型中的 OneToManyField(不存在)来表示这种关系?我来自 Hibernate/JPA,在那里声明一对多关系就像:

What would I replace OneToManyField (which doesn't exist) with in the model to represent this kind of relationship? I'm coming from Hibernate/JPA where declaring a one-to-many relationship was as easy as:

@OneToMany
private List<PhoneNumber> phoneNumbers;

我如何在 Django 中表达这一点?

How can I express this in Django?

推荐答案

要在 Django 中处理一对多关系,您需要使用 ForeignKey.

To handle One-To-Many relationships in Django you need to use ForeignKey.

有关 ForeignKey 的文档非常全面,应该可以回答您的所有问题:

The documentation on ForeignKey is very comprehensive and should answer all the questions you have:

https://docs.djangoproject.com/en/3.2/ref/models/fields/#foreignkey

示例中的当前结构允许每个 Dude 有一个号码,每个号码属于多个 Dudes(与 Business 相同).

The current structure in your example allows each Dude to have one number, and each number to belong to multiple Dudes (same with Business).

如果您想要反向关系,则需要向 PhoneNumber 模型添加两个 ForeignKey 字段,一个是 Dude,一个是 Business.这将允许每个号码属于一个 Dude 或一个企业,并且让 Dudes 和企业能够拥有多个号码.我想这可能就是你所追求的.

If you want the reverse relationship, you would need to add two ForeignKey fields to your PhoneNumber model, one to Dude and one to Business. This would allow each number to belong to either one Dude or one Business, and have Dudes and Businesses able to own multiple Numbers. I think this might be what you are after.

class Business(models.Model):
    ...
class Dude(models.Model):
    ...
class PhoneNumber(models.Model):
    dude = models.ForeignKey(Dude)
    business = models.ForeignKey(Business)

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

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