Reputation: 533
I want to perform an update operation on a Django queryset conditionally such that the value of an attribute is updated only when it matches a condition otherwise keep the value it is currently having.
I know that conditional updates in django are performed using Case, When, then, default but not getting how to keep the existing value for the default case. I tried leaving default from the query but then it throws an error.
I want something like the following. Say there are 4 types of schemes: PRO, REGULAR, HOME, FREE.
Customer.objects.filter(age__lte=18)\
.update(type=Case(When(type=HOME,
then=FREE),
default=<keep current value>),
subscribed=False)
Upvotes: 0
Views: 1349
Reputation: 533
Okay so I can use a F()
object for it. eg. F('field_name')
So, the query I need becomes:
Customer.objects.filter(age__lte=18)\
.update(type=Case(When(type=HOME,
then=FREE),
default=F('type')),
subscribed=False)
Upvotes: 1