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.
Use the not Operator to Negate a Boolean in Python The not operator in Python helps return the negative or the opposite value of a given boolean value. This operator is used by placing the not operator as a prefix of a given boolean expression.
The ! is a logical operator that will convert a value to its opposite boolean. Since JavaScript will coerce values, it will “convert” a value to its truthy/falsey form and return the opposite boolean value.
Numpy Array and ~ to Negate Boolean in Python By using the numpy array library and the bitwise operator '~' pronounced as a tilde. We can easily negate a Boolean value in Python. The tilde operator takes a one-bit operand and returns its complement. If the operand is 1, it returns 0, and vice-versa.
The logical NOT ( ! ) operator (logical complement, negation) takes truth to falsity and vice versa. It is typically used with boolean (logical) values. When used with non-Boolean values, it returns false if its single operand can be converted to true ; otherwise, returns true .
You can do this:
item.active = not item.active
That should do the trick :)
I think you want
item.active = not item.active
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With