Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Succinct way of updating a single field of a django model object

To update (and save) the field on an object you do:

>>> product = Product.objects.get(name='Venezuelan Beaver Cheese')
>>> product.number_sold = 4
>>> product.save()

Is there a way to compress the last two lines into a single line, like:

product.update(number_sold=4)
like image 818
pseudosudo Avatar asked May 11 '12 18:05

pseudosudo


People also ask

How do I update model fields 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.

How do I add a field in Django?

To answer your question, with the new migration introduced in Django 1.7, in order to add a new field to a model you can simply add that field to your model and initialize migrations with ./manage.py makemigrations and then run ./manage.py migrate and the new field will be added to your DB.

What is PK in Django models?

pk is short for primary key, which is a unique identifier for each record in a database. Every Django model has a field which serves as its primary key, and whatever other name it has, it can also be referred to as "pk".


3 Answers

Yup.

Product.objects.filter(name='Venezuelan Beaver Cheese').update(number_sold=4)

If you have a model instance you changed and want to save only specific fields to the database, do that:

product.name = "New name of the product"
product.save(update_fields=['name'])
like image 60
Steve K Avatar answered Oct 26 '22 14:10

Steve K


@Lovelive's answer is the best way to go. The only downside is that you don't get the instance with that. So you still need the product = Product.objects.get(...) line if you need product for anything else. However, it does cover the use-case scenario of "compress the last two lines into a single line" perfectly.

Just to play devil's advocate, you could also add a method to your model:

class Product(models.Model):
    ...
    def update(self, **kwargs):
        for k, v in kwargs.iteritems():
            setattr(self, k, v)
        self.save()
like image 37
Chris Pratt Avatar answered Oct 26 '22 14:10

Chris Pratt


Depending on the situation this is also an alternative:

product.save(update_fields=["number_sold"])
like image 24
Emanuele Paolini Avatar answered Oct 26 '22 15:10

Emanuele Paolini