DRF。尝试创建需要另一个 DB 对象实例的记录,并不断获取 "int() argument must be a string..."

DRF. Trying to create a record that requires an instance of another DB object, and keep getting "int() argument must be a string..."

我是 Django 和 DRF 的新手,我真的很困惑。

我正在尝试在具有外键的 table 中创建记录。我们会说模型看起来像这样:

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'

真的不明白,因为我确定我在其他地方创建过这样的记录。

试试这个:

Bar.objects.create(
  bar_id = "A1",
  name = "John",
  foo_id = 7
)

或者这个:

bar = Bar(bar_id="A1", name="John")
bar.foo_id = 7
bar.save()

首先当你使用 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)
)