Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Invert boolean field in update operations with F()

Tags:

django

I need, through an update operation, revert a boolean value.

I tried:

Item.objects.filter(serial__in=license_ids).update(renewable=not F('renewable'))

But it doesn't work. I made sure the fields are not set to null.

like image 404
Ev. Avatar asked Nov 03 '16 12:11

Ev.


2 Answers

You can also do:

Item.objects.filter(serial__in=license_ids).update(renewable=Q(renewable=False))

when renewable is True => Q object condition will give False

when renewable is False => Q object condition will give True

like image 132
Rishabh Gupta Avatar answered Sep 29 '22 13:09

Rishabh Gupta


Not is not supported here. You will have to use Case When

from django.db.models import Case, Value, When

Item.objects.filter(serial__in=license_ids
).update(renewable=Case(
    When(renewable=True, then=Value(False)),
    default=Value(True))
    )
)
like image 26
e4c5 Avatar answered Sep 29 '22 11:09

e4c5