Circular dependency in Django ForeignKey?

后端 未结 2 611
醉酒成梦
醉酒成梦 2021-01-22 05:34

I have two models in Django:

A:
  b = ForeignKey(\"B\")

B:
  a = ForeignKey(A)

I want these ForeignKeys to be non-NULL.

However, I can

相关标签:
2条回答
  • 2021-01-22 05:58

    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.

    0 讨论(0)
  • 2021-01-22 06:04

    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.

    0 讨论(0)
提交回复
热议问题