How do I perform a dynamic Django queryset update?
I have the following model:
class Book(models.Model):
title = models.CharField(max_length=100)
quantity = models.IntegerField()
in_stock = models.BooleanField()
I have a form which allows me to update the quantity and stock of multiple selected books:
Quantity:
In Stock:
List of Books:
1. Eat Pray and Love
2. Twilight
In my views, I can update a querylist of Books like the following:
quantity = form.cleaned_data['quantity']
in_stock = form.cleaned_data['in_stock']
if quantity:
selected_books.update(quantity=quantity)
if in_开发者_Python百科stock:
selected_books.update(in_stock=in_stock)
I am basically doing a batch update only if the field has been entered. The above requires 2 separate sql update statements. Is there a way to call use a single sql statement regardless of the number of entered fields?
Build a dict, then do it at once with kwarg expansion.
d = {}
if quantity:
d['quantity'] = quantity
...
selected_books.update(**d)
精彩评论