vascop vascop -4 years ago 97
Python Question

Toggle boolean fields from a Queryset using F objects

I've tried these queries with these results:

queryset.update(done=not F('boolean'))
{'time': '0.001', 'sql': u'UPDATE "todo_item" SET "done" = True'}

{'time': '0.001', 'sql': u'UPDATE "todo_item" SET "done" = False'}

What I would like is something like this:

{'time': '0.002', 'sql': u'UPDATE "todo_item" SET "done" = "todo_item"."done"'}

But with

SET "done" = !"todo_item"."done"

to toggle the boolean value

Answer Source

I am developing django-orm extension, and have already partially implemented the solution to your problem.

>>> from django_orm.expressions import F
>>> from niwi.models import TestModel
>>> TestModel.objects.update(done=~F('done'))

# SQL:
UPDATE "niwi_testmodel" SET "done" = NOT "niwi_testmodel"."done"; args=()

Is a partial solution and not very clean. And so far only for postgresql. In a while I'll see how to improve it.

Update: now improved and works on postgresql, mysql and sqlite.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download