Label : diff

django / query expression / negate

By | | Tech | 2 commentaren

Suppose you have an is_enabled boolean in your Django model.

class Rule(models.Model):
    is_enabled = models.BooleanField(blank=True)
    # other exciting fields here

And now imagine you want to negate the is_enabled values. Something you would easily do in SQL, with: UPDATE myapp_rule SET is_enabled = NOT is_enabled;

The Django F-syntax is nice, and looks like it should be up for the task.

Let's sum up a couple of attempts:

Rule.objects.update(is_enabled=(not F('is_enabled')))

No! You get this:
UPDATE myapp_rule SET is_enabled = true;

Rule.objects.update(is_enabled=(True ^ F('is_enabled')))

No! You get this:
unsupported operand type ...