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?
Use update_fields in save() If you would like to explicitly mention only those columns that you want to be updated, you can do so using the update_fields parameter while calling the save() method. You can also choose to update multiple columns by passing more field names in the update_fields list.
CharField is a commonly-defined field used as an attribute to reference a text-based database column when defining Model classes with the Django ORM. The Django project has wonderful documentation for CharField and all of the other column fields.
Field models are used to calculate the values of field functions under given boundary and loading conditions. Field functions are physical quantities which depend on their geometrical location, such as temperature (a scalar field) or velocity (a vector field).
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With