[Fixed]-Succinct way of updating a single field of a django model object

34đź‘Ť

âś…

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'])
👤Steve K

7đź‘Ť

@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()
👤Chris Pratt

0đź‘Ť

Depending on the situation this is also an alternative:

product.save(update_fields=["number_sold"])

Leave a comment