Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update only specific fields in a 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 an error IntegrityError: PRIMARY KEY must be unique.

Am I right with this method to update?

like image 692
Registered User Avatar asked Dec 16 '12 12:12

Registered User


People also ask

How do I update a specific field in Django?

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.

WHAT IS models CharField?

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.

What are model 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).


1 Answers

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) 
like image 115
Alasdair Avatar answered Oct 12 '22 08:10

Alasdair