I have a model instance which has a boolean field on it. What I want to achieve is to switch the value from True to False or vice versa.
Surely, I can just write:
inst = Model.objects.get(id=1)
inst.boolean_field = not inst.boolean_field
inst.save()
But there are 2 queries: one for fetching and another one for updating.
I'd like just to switch the values, but the following does not seem to work:
Model.objects.filter(id=1).update(boolean_field=not F("boolean_field"))
I'm pretty sure that I'm doing something wrong or it's just not possible.
You can use Case
instead:
from django.db.models import Case, Value, When
queryset.update(active=Case(
When(active=True, then=Value(False)),
When(active=False, then=Value(True)),
))
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