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)
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.
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.
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".
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'])
@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()
Depending on the situation this is also an alternative:
product.save(update_fields=["number_sold"])
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