不需要参照完整性的Django ForeignKey? [英] Django ForeignKey which does not require referential integrity?

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

问题描述

我想在 django 模型中设置一个 ForeignKey 字段,该字段有时会指向另一个表.但我希望可以在该字段中插入一个 id,该 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/dev/ref/models/fields/#django.db.models.ForeignKey.db_constraint

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

或者,如果您希望可以为 null 并且不强制执行参照完整性:

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天全站免登陆