DjangoForeignKey 中的循环依赖?
我在 Django 中有两个模型:
A:
b = ForeignKey("B")
B:
a = ForeignKey(A)
我希望这些外键为非 NULL。
但是,我无法创建对象,因为在我 save() 之前它们没有 PrimaryKey。但如果没有其他对象 PrimaryKey,我就无法保存。
如何创建相互引用的 A 和 B 对象? 如果可能的话,我不想允许 NULL。
I have two models in Django:
A:
b = ForeignKey("B")
B:
a = ForeignKey(A)
I want these ForeignKeys to be non-NULL.
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.
How can I create an A and B object that refer to each other?
I don't want to permit NULL if possible.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果这确实是一个引导问题,而不是在正常使用过程中会再次出现的问题,那么您可以创建一个固定装置,用一些初始数据预先填充您的数据库。夹具处理代码包括数据库层的解决方法,以解决前向引用问题。
如果这不是引导问题,并且您想要定期在新对象之间创建这些循环关系,那么您可能应该重新考虑您的模式 - 其中一个外键可能是不必要的。
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 在 ORM 中提供了很好的帮助器来引用相应的对象。
使用 Django 的
OneToOneField
:然后你可以像这样简单地引用它们:
此外,你可以查看 django-annoying 的
AutoOneToOneField
,如果实例上不存在关联对象,它将在保存时自动创建关联对象。如果您的问题不是一对一关系,您应该澄清,因为几乎可以肯定有比相互外键更好的数据建模方法。否则,无法避免在保存时设置必填字段。
It sounds like you're talking about a one-to-one relationship, in which case it is unnecessary to store the foreign key on both tables. In fact, Django provides nice helpers in the ORM to reference the corresponding object.
Using Django's
OneToOneField
:Then you can simply reference them like so:
In addition, you may look into django-annoying's
AutoOneToOneField
, which will auto-create the associated object on save if it doesn't exist on the instance.If your problem is not a one-to-one relationship, you should clarify because there is almost certainly a better way to model the data than mutual foreign keys. Otherwise, there is not a way to avoid setting a required field on save.