我如何将数据插入一个模型的字段中,即与另一个模型映射的OnetoOneField

时间:2019-04-15 09:54:43

标签: django postgresql

这些是我的模型,其中eda_defect_id中的eda_detail是引用模型defect_details的一对一字段。

class defect_details(models.Model):
    defect_id = models.CharField(primary_key=True,max_length=20)
    description = models.CharField(max_length=256)


class eda_detail(models.Model):
    eda_defect_id = models.OneToOneField('defects.defect_details',primary_key=True, on_delete=models.PROTECT)
    analysis_writeup = models.TextField(blank=True, null=True)

在我的代码中,我试图插入模型中,但出现错误:

from defects.models import defect_details
from edainfo.models import eda_detail

defect_id = "Jira-SMSV-512"
description = "Hello There"
defect_obj = defect_details(defect_id=defect_id, description=description)
defect_obj.save()

eda_obj = eda_detail(eda_defect_id=defect_id)
eda_obj.save()
  

错误:   ValueError:无法分配“'Jira-SMSV-512'”:“ eda_detail.eda_defect_id”必须是“ defect_details”实例。

1 个答案:

答案 0 :(得分:0)

您的eda_detail模型在defect_details模型上具有OneToOne,因此在保存数据时,您只能将defect_details的实例而不是字符串传递给eda_detail,

所以您的代码应该像

eda_obj = eda_detail(eda_defect_id=defect_obj)

,然后使用eda_obj.save()

保存

以django文档为例,Django OneToOne