我確定我在這里遺漏了一些東西。
我確實有兩個模型,Foo 和 Bar 就像這樣
class Foo(models.Model):
bar = models.OneToOneField(Bar)
..
class Bar(models.Model):
foo = models.OneToOneField(Foo)
..
現在我必須為它們創建新實體,它們將被映射為 1-1。創建一個實體,它需要我將名稱映射到另一個尚不存在的實體。
遇到這種情況怎么辦?有沒有辦法預先或 s.th. 創建一個空實體?
foo_instance = Foo(bar=bar_instance)
foo_instance.save()
# won't work since bar_instance not yet created
..
uj5u.com熱心網友回復:
你應該只宣告一次關系。
class Foo(models.Model):
..
class Bar(models.Model):
foo = models.OneToOneField(Foo)
..
然后,您在實體的兩側呼叫您的物件。
foo_instance = Foo()
bar_instance = Bar(foo=foo.instance)
bar_instance.foo
foo_instance.bar # As the name of the class, but in lowercase
這里的檔案
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/360201.html
標籤:姜戈
