Circular dependency in Django ForeignKey?

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-31 02:56:10

问题


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.


回答1:


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.




回答2:


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:

class A(models.Model):
    <snip>

class B(models.Model):
    a = OneToOneField(A)

Then you can simply reference them like so:

a = A()
a.save()
b = B(a=a)
b.save()

print a.b
print b.a

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.



来源:https://stackoverflow.com/questions/7909428/circular-dependency-in-django-foreignkey

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!