[Django]-Django QuerySet querying or filtering "Odd" and/or "Even" value in a particular field

14👍

In Django >1.8 you could use F() expressions:

# ParkingLots with even numbered lot_numbers
ParkingLot.objects.annotate(odd=F('lot_number') % 2).filter(odd=False)  

# ParkingLots with odd numbered lot_numbers
ParkingLot.objects.annotate(odd=F('lot_number') % 2).filter(odd=True)  

This won’t work in older versions of Django though.

3👍

This query can be done in Database Layer.

even_lots = ParkingLot.objects.filter(id__iregex='^\d*[02468]$') # Hit Database
odd_lots = ParkingLot.objects.filter(id__iregex='^\d*[13579]$') # Hit Database

Behind the scene, the even queryset will create the following SQL Query.

SELECT *
FROM parkinglot
WHERE id REGEXP '^\d*[02468]$'

Provided that we are interested in odd XOR even. I believed this should be the preferred method. However, I’m not sure, but heard that regex is slow.

Update

Check @jproffitt, That should be the best.

👤Yeo

-1👍

This query can be done in Python level.

parking_lots = list(ParkingLot.objects.all()) # Hit Database once
odd_lots = parking_lots[0::2]
even_lots = parking_lots[1::2]
👤Yeo

Leave a comment