使用 F 对象切换查询集中的布尔字段
我已经尝试过这些查询并得到以下结果:
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" = False'}
我想要的是这样的:
queryset.update(done=F('done'))
{'time': '0.002', 'sql': u'UPDATE "todo_item" SET "done" = "todo_item"."done"'}
但是要
SET "done" = !"todo_item"."done"
切换布尔值
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" = False'}
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我正在开发 django-orm 扩展,并且已经部分实现了您问题的解决方案。
https://github.com/niwibe/django-orm
是部分解决方案,不是很干净。到目前为止仅适用于 postgresql。过段时间我会看看如何改进它。
更新:现已改进并适用于 postgresql、mysql 和 sqlite。
I am developing django-orm extension, and have already partially implemented the solution to your problem.
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.
这是标准方法,效果很好
条件表达式
我将用一个更简单的例子来简单地解释它:)
假设我们有 Restaurant 对象(模型),它有 is_close 字段(BooleanField)
并且我们想要切换is_close 对于具有 pk=1 的对象,此代码片段执行以下操作:
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:
对于布尔值,您可以使用更Pythonic的
not F()
,对于字段上的位否定,请使用~F()
For boolean values, you can use the more Pythonic
not F()
and for bit negation on fields, use~F()