1

I have a model with double columns as primary key. I do a filter on it and get the records I want, change a field and save it. As I know save will update the record and does not create a new instance of the model in db. so It should be all okay but I'm stuck with an integrityError Duplicate entry '10-2' for key 'PRIMARY' when I try to save the record

Here is the code snippet:

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

And here is my model:

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'),)
Hamid Sajjadi
  • 113
  • 2
  • 10
  • 1
    `AnalysisResult.objects.filter(request=req.request_id)` filter by primary key is equal some value you should to get only one record is it? why you do loop? – Brown Bear Jan 08 '18 at 15:30
  • @BearBrown `unique_together = (('request', 'targetcode'),)` request_id + targetcode_id makes a record unique together. – Hamid Sajjadi Jan 08 '18 at 16:23

1 Answers1

1

Ah, yes, welcome to one of django's strongest opinions: all tables/models should have a single primary key field that can be used for updates. If you don't have this, you must write raw SQL for the update since save will assume that there is an implicit primary key field called id to use in the where clause.

2ps
  • 15,099
  • 2
  • 27
  • 47