更新记录时出现Django IntegrityError

时间:2018-01-08 14:30:55

标签: python django python-3.x django-models

我有一个双列作为主键的模型。我对它进行过滤并获取我想要的记录,更改字段并保存。据我所知,save将更新记录,并且不会在db中创建模型的新实例。所以应该没问题但我在尝试保存记录时遇到了integrityError Duplicate entry '10-2' for key 'PRIMARY'

以下是代码段:

analysis = AnalysisResult.objects.filter(request=req.request_id)
for anal in analysis:
    anal.analysisresult_path = some_string
    anal.save() #this line is where the error occurs

这是我的模特:

class AnalysisResult(models.Model):

    analysisresult_path = models.CharField(db_column='analysisResult_path', max_length=255, blank=True,
                                       null=True)  # Field name made lowercase.
    detectionresult_path = models.CharField(db_column='detectionResult_path', max_length=255, blank=True,
                                        null=True)  # Field name made lowercase.
    targetcode = models.ForeignKey('TagetCode', models.DO_NOTHING,
                               db_column='targetCode_id')  # Field name made lowercase.
    request = models.ForeignKey('Request', models.DO_NOTHING, primary_key=True)


    class Meta:
        managed = False
        db_table = 'analysis_result'
        unique_together = (('request', 'targetcode'),)

1 个答案:

答案 0 :(得分:1)

啊,是的,欢迎来到django's strongest opinions之一:所有表/模型都应该有一个可用于更新的主键字段。如果你没有这个,你必须为更新编写原始SQL,因为save将假定在where子句中有一个名为id的隐式主键字段。