Only update specific fields in models. Model

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 the error IntegrityError: PRIMARY KEY must be unique .

Am I right with this method for updating?

+47
django django-models django-views django-database
Dec 16 '12 at 12:21
source share
2 answers

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

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

Note that update_fields is a new feature in Django 1.5. In earlier versions, you could use update() instead:

 Survey.objects.filter(pk=survey.pk).update(active=True) 
+87
Dec 16 '12 at 12:59
source share

Usually, the correct way to update certain fields in one or more instances of a model is to use the update() method in the appropriate set of queries. Then you do something like this:

 affected_surveys = Survey.objects.filter( # restrict your queryset by whatever fits you # ... ).update(active=True) 

Thus, you no longer need to call save() on your model because it is automatically saved. In addition, the update() method returns the number of survey instances affected by your update.

+11
Dec 16 '12 at 12:36
source share



All Articles