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
- Can Django run on Gunicorn alone (no Apache or nginx)?
- Background processing in Django without Celery
- How to ensure task execution order per user using Celery, RabbitMQ and Django?
- Use of unicode in Django
0đź‘Ť
Depending on the situation this is also an alternative:
product.save(update_fields=["number_sold"])
👤Emanuele Paolini
- Improving Performance of Django ForeignKey Fields in Admin
- Where do I import the `DoesNotExist` exception in Django 1.10 from?
- Python Django custom template tags register.assignment_tag not working
- Select Children of an Object With ForeignKey in Django?
- Pycharm remote project with virtualenv
Source:stackexchange.com