Django ForeignKey不需要引用完整性? [英] Django ForeignKey which does not require referential integrity?

查看:550
本文介绍了Django ForeignKey不需要引用完整性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在一个django模型中设置一个 ForeignKey 字段,指向其他表格的某个时间。但是我希望在这个字段中插入一个id可以是另一个表中可能不存在的条目。所以如果这行存在于另一个表中,我想获得ForeignKey关系的所有好处。但如果没有,我希望这只是一个数字。

I'd like to set up a ForeignKey field in a django model which points to another table some of the time. But I want it to be okay to insert an id into this field which refers to an entry in the other table which might not be there. So if the row exists in the other table, I'd like to get all the benefits of the ForeignKey relationship. But if not, I'd like this treated as just a number.

这是可能吗?这是什么普通关系?

Is this possible? Is this what Generic relations are for?

推荐答案

这个问题很久以前被问到,但对于新来的人现在有一个建立通过在您的ForeignKey上设置db_constraint = False来处理此问题:

This question was asked a long time ago, but for newcomers there is now a built in way to handle this by setting db_constraint=False on your ForeignKey:

https://docs.djangoproject.com/en/1.9/ref/models/fields/#django.db.models.ForeignKey。 db_constraint

customer = models.ForeignKey('Customer', db_constraint=False)

或者如果您想要为空,并且不执行参照完整性:

or if you want to to be nullable as well as not enforcing referential integrity:

customer = models.ForeignKey('Customer', null=True, blank=True, db_constraint=False) 

如果我们无法保证以正确的顺序创建关系,我们会使用这种方式。

We use this in cases where we cannot guarantee that the relations will get created in the right order.

编辑:更新链接

这篇关于Django ForeignKey不需要引用完整性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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