Update only specific fields in a models.Model

Registered User picture Registered User · Dec 16, 2012 · Viewed 100.1k times · Source

I have a model

class Survey(models.Model):
    created_by = models.ForeignKey(User)
    question = models.CharField(max_length=150)
    active = models.NullBooleanField()
    def __unicode__(self):
        return self.question

and now I want to update only the active field. So I do this:

survey = get_object_or_404(Survey, created_by=request.user, pk=question_id)
survey.active = True
survey.save(["active"]) 

Now I get an error IntegrityError: PRIMARY KEY must be unique.

Am I right with this method to update?

Answer

Alasdair picture Alasdair · Dec 16, 2012

To update a subset of fields, you can use update_fields:

survey.save(update_fields=["active"]) 

The update_fields argument was added in Django 1.5. In earlier versions, you could use the update() method instead:

Survey.objects.filter(pk=survey.pk).update(active=True)