I have a Django site, with an Item
object that has a boolean property active
. I would like to do something like this to toggle the property from False to True and vice-versa:
我有一个Django站点,其中包含一个具有布尔属性活动的项对象。我想做这样的事情,将属性从False切换到True,反之亦然:
def toggle_active(item_id):
item = Item.objects.get(id=item_id)
item.active = !item.active
item.save()
This syntax is valid in many C-based languages, but seems invalid in Python. Is there another way to do this WITHOUT using:
这种语法在许多基于c的语言中都是有效的,但在Python中似乎是无效的。有没有另一种方法可以不用:
if item.active:
item.active = False
else:
item.active = True
item.save()
The native python neg()
method seems to return the negation of an integer, not the negation of a boolean.
本机python neg()方法似乎返回整数的否定,而不是布尔值的否定。
Thanks for the help.
谢谢你的帮助。
6 个解决方案
#1
95
You can do this:
你可以这样做:
item.active = not item.active
That should do the trick :)
这应该可以达到目的:
#2
13
I think you want
我认为你想要的
item.active = not item.active
#3
12
item.active = not item.active
is the pythonic way
项。主动=不项目。主动是勾股定理
#4
9
Another (less
concise
readable, more arithmetic) way to do it would be:
另一种(不那么简明、可读、更算数)的方法是:
item.active = bool(1 - item.active)
#5
6
The negation for booleans is not
.
布尔人的否定是否定的。
def toggle_active(item_id):
item = Item.objects.get(id=item_id)
item.active = not item.active
item.save()
Thanks guys, that was a lightning fast response!
谢谢大家,这是一个闪电般的快速反应!
#6
5
Its simple to do :
很简单:
item.active = not item.active
So, finally you will end up with :
最后你会得到:
def toggleActive(item_id):
item = Item.objects.get(id=item_id)
item.active = not item.active
item.save()
#1
95
You can do this:
你可以这样做:
item.active = not item.active
That should do the trick :)
这应该可以达到目的:
#2
13
I think you want
我认为你想要的
item.active = not item.active
#3
12
item.active = not item.active
is the pythonic way
项。主动=不项目。主动是勾股定理
#4
9
Another (less
concise
readable, more arithmetic) way to do it would be:
另一种(不那么简明、可读、更算数)的方法是:
item.active = bool(1 - item.active)
#5
6
The negation for booleans is not
.
布尔人的否定是否定的。
def toggle_active(item_id):
item = Item.objects.get(id=item_id)
item.active = not item.active
item.save()
Thanks guys, that was a lightning fast response!
谢谢大家,这是一个闪电般的快速反应!
#6
5
Its simple to do :
很简单:
item.active = not item.active
So, finally you will end up with :
最后你会得到:
def toggleActive(item_id):
item = Item.objects.get(id=item_id)
item.active = not item.active
item.save()