Django QuerySet querying or filtering “Odd” and/or

2020-07-18 11:27发布

问题:

# Example
from django.db import models

class ParkingLot(models.Model):
    lot_number = models.IntegerField()
    is_reserved = models.BooleanField()

I'm interested in Odd xor Even lot_number. What's the recommended way to filter that in Django?

I've posted some answer below.


Challenge

Does anyone know if we can use a direct comparison something like F('lot_number') % 2 == 0 technique?

回答1:

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.



回答2:

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.



回答3:

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]