Is there a way to negate a boolean returned to variable?
PythonDjangoPython Problem Overview
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:
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:
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.
Thanks for the help.
Python Solutions
Solution 1 - Python
You can do this:
item.active = not item.active
That should do the trick :)
Solution 2 - Python
I think you want
item.active = not item.active
Solution 3 - Python
item.active = not item.active
is the pythonic way
Solution 4 - Python
Another (less concise readable, more arithmetic) way to do it would be:
item.active = bool(1 - item.active)
Solution 5 - Python
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!
Solution 6 - Python
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()