I'm new to Django and DRF and I'm really struggling with something.
I'm attempting to create a record in a table that has a foreign key. We'll say the models looks like this:
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',
)
When I try this:
Bar.objects.create(
bar_id = "A1",
name = "John",
foo = 5
)
I get the error that I would expect:
Cannot assign "5": "Bar.foo" must be a "Foo" instance.
But if I try:
Bar.objects.create(
bar_id = "A1",
name = "John",
foo = Foo.objects.get(foo_id=7)
)
I get:
int() argument must be a string, a bytes-like object or a number, not 'Foo'
Really don't understand as I'm sure I've created records like this elsewhere.
CodePudding user response:
Try this:
Bar.objects.create(
bar_id = "A1",
name = "John",
foo_id = 7
)
or this:
bar = Bar(bar_id="A1", name="John")
bar.foo_id = 7
bar.save()
CodePudding user response:
first you should null=True when you are using SET_NUll
foo = models.ForeignKey(
Foo,
models.SET_NULL,
null=True,
related_name='rel', )
Secound you can use below approaches
Bar.objects.create(
bar_id = "A1",
name = "John",
foo_id = 5
)
and your secound approach is correct
Bar.objects.create(
bar_id = "A1",
name = "John",
foo = Foo.objects.get(foo_id=7)
)