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
- [Django]-Why django contains a lot of '__init__.py'?
- [Django]-How to cast Django form to dict where keys are field id in template and values are initial values?
- [Django]-How to query for distinct groups of entities which are joined via a self-referential many-to-many table?
-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
- [Django]-Problems with deploying fabric for mezzanine
- [Django]-Access Django App on AWS ec2 host
- [Django]-Get all values from Django QuerySet plus additional fields from a related model
- [Django]-How can I know if a email is sent correctly with Django/Python?
Source:stackexchange.com