这些是我的模型,其中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”实例。
答案 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