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'}
queryset.update(done=(F('boolean')==False))
{'time': '0.001', 'sql': u'UPDATE "todo_item" SET "done" = Fals开发者_如何学编程e'}
What I would like is something like this:
queryset.update(done=F('done'))
{'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
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=()
https://github.com/niwibe/django-orm
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.
This is the standard way and works pretty well
conditional expressions
I'll explain it simply with an even simpler example :)
suppose we have Restaurant objects (model), which has is_closed field (BooleanField)
and we want to toggle is_closed for object with pk=1, this snippet does that:
r1 = Restaurant.objects.get(pk=1).update(
is_closed=Case(
When(is_closed=True, then=False),
default=True
))
#update_status
update_status = (
"UPDATE csv SET status = (NOT csv.status) "
"WHERE id = %s")
print(random_number)
cursor.execute(update_status, (random_number))
print("update_status")
For boolean values, you can use the more Pythonic not F()
and for bit negation on fields, use ~F()
精彩评论