我是 Django 和 DRF 的新手,我真的在為某些事情苦苦掙扎。
我正在嘗試在具有外鍵的表中創建記錄。我們會說模型看起來像這樣:
class Foo(models.Model):
foo_id = models.IntegerField(
primary_key=True,
)
name = models.CharField(
max_length=256,
)
class Bar(models.Model):
bar_id = models.CharField(
primary_key=True,
max_length=256
)
name = models.CharField(
max_length=256,
)
foo = models.ForeignKey(
Foo,
models.SET_NULL,
related_name='rel',
)
當我嘗試這個時:
Bar.objects.create(
bar_id = "A1",
name = "John",
foo = 5
)
我得到了我期望的錯誤:
Cannot assign "5": "Bar.foo" must be a "Foo" instance.
但如果我嘗試:
Bar.objects.create(
bar_id = "A1",
name = "John",
foo = Foo.objects.get(foo_id=7)
)
我得到:
int() argument must be a string, a bytes-like object or a number, not 'Foo'
真的不明白,因為我確定我在其他地方創造了這樣的記錄。
uj5u.com熱心網友回復:
試試這個:
Bar.objects.create(
bar_id = "A1",
name = "John",
foo_id = 7
)
或這個:
bar = Bar(bar_id="A1", name="John")
bar.foo_id = 7
bar.save()
uj5u.com熱心網友回復:
首先你應該在使用 SET_NUll 時 null=True
foo = models.ForeignKey(
Foo,
models.SET_NULL,
null=True,
related_name='rel', )
其次,您可以使用以下方法
Bar.objects.create(
bar_id = "A1",
name = "John",
foo_id = 5
)
你的第二種方法是正確的
Bar.objects.create(
bar_id = "A1",
name = "John",
foo = Foo.objects.get(foo_id=7)
)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/404793.html
標籤:
下一篇:如何列出同一日期的物件?
