Django ForeignKey中的循环依赖关系? [英] Circular dependency in Django ForeignKey?

查看:79
本文介绍了Django ForeignKey中的循环依赖关系?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Django中有两个模型:

I have two models in Django:

A:
  b = ForeignKey("B")

B:
  a = ForeignKey(A)

我想要这些ForeignKey是非NULL。

I want these ForeignKeys to be non-NULL.

但是,我无法创建对象,因为在我保存()之前它们没有主键。但是如果没有其他对象PrimaryKey,我将无法保存。

However, I cannot create the objects because they don't have a PrimaryKey until I save(). But I cannot save without having the other objects PrimaryKey.

如何创建相互引用的A和B对象?
如果可能的话,我不想允许NULL。

How can I create an A and B object that refer to each other? I don't want to permit NULL if possible.

推荐答案

如果这确实是自举问题,而不是什么在正常使用期间会再次发生,您只需创建一个固定装置,即可使用一些初始数据来预先填充数据库。夹具处理代码包括数据库层的解决方法,以解决前向引用问题。

If this is really a bootstrapping problem and not something that will reoccur during normal usage, you could just create a fixture that will prepopulate your database with some initial data. The fixture-handling code includes workarounds at the database layer to resolve the forward-reference issue.

如果这不是自举问题,您将需要定期在新对象之间创建这些循环关系,您可能应该重新考虑您的架构-外键之一可能是不必要的。

If it's not a bootstrapping problem, and you're going to want to regularly create these circular relations among new objects, you should probably either reconsider your schema--one of the foreign keys is probably unnecessary.

这篇关于Django ForeignKey中的循环依赖关系?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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