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?
This question is related to
django
django-models
django-views
django-database
Usually, the correct way of updating certain fields in one or more model instances is to use the update()
method on the respective queryset. Then you do something like this:
affected_surveys = Survey.objects.filter(
# restrict your queryset by whatever fits you
# ...
).update(active=True)
This way, you don't need to call save()
on your model anymore because it gets saved automatically. Also, the update()
method returns the number of survey instances that were affected by your update.
Source: Stackoverflow.com