Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Switching value of boolean field with update method in Django

Tags:

django

models

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.

like image 995
aemdy Avatar asked Sep 12 '25 18:09

aemdy


1 Answers

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)),
))
like image 137
Max Malysh Avatar answered Sep 15 '25 08:09

Max Malysh