开发者

Django - saving two records at the same time with a foreign key relation

开发者 https://www.devze.com 2023-03-11 21:21 出处:网络
I want to be able to save two records in two database tables at the same time with one of the tables having foreign key relation to the other table.

I want to be able to save two records in two database tables at the same time with one of the tables having foreign key relation to the other table.

models.py

class Model1(models.Model):
    Modlel1Filed1 = models.CharField()

class Model2 (开发者_Go百科models.Model):
    Model2Filed1 = models.ForeignKey(Model1)
    Modle2Field2 = models.CharField()

Below is how I save the data using Model1:

p = Model1.objects.create(Model1Filed1=some_data_here)
p.save()

For Model2 I tried:

p = Model1.objects.get(pk=p.pk)
f = Model2.objects.create(Model2Filed1=p.id, Modle2Field2=some_data)
f = save()

but I'm getting an error like this:

Cannot assign "78": "Model2.Model2Filed1" must be a "Model1" instance.

Any ides?


The error message is pretty clear: "Model2.Model2Filed1" must be a "Model1" instance:

f = Model2.objects.create(Model2Filed1=p, Modle2Field2=some_data)

changed Model2Filed1=p.id to Model2Filed1=p

0

精彩评论

暂无评论...
验证码 换一张
取 消