10.11. Operator Numerical

  • -obj - neg

  • +obj - pos

  • ~obj - invert

10.11.1. About

Table 10.10. Numerical Operator Overload

Operator

Method

-obj

obj.__neg__()

+obj

obj.__pos__()

~obj

obj.__invert__()

10.11.2. Operator

  • operator.neg(obj) - neg - -obj

  • operator.pos(obj) - pos - +obj

  • operator.invert(obj) - invert - ~obj

>>> import operator
>>> operator.neg(1)
-1
>>> operator.pos(1)
1
>>> operator.invert(1)
-2

10.11.3. Use Case - 1

  • Django ORM Q objects

  • Django QuerySet filtering

  • Combine multiple conditions with AND, OR, NOT, invert

from django.db.models import Q
from myapp.models import Customer


alice = Q(firstname='Alice')
apricot = Q(lastname='Apricot')
bob = Q(firstname='Bob')
blackthorn = Q(lastname='Blackthorn')

aapricot = alice & apricot
bblackthorn = bob & blackthorn

Customer.objects.filter(aapricot | bblackthorn)
<QuerySet [<Customer: Alice Apricot>, <Customer: Bob Blackthorn>]>

Customer.objects.filter( (aapricot|bblackthorn) & ~(alice&apricot) )
<QuerySet [<Customer: Bob Blackthorn>]>