我在模型中有一個欄位型別 Json,但我不能確定它是整數還是字串,有效的長版本是:
cars = Car.objects.filter(
user_id=self.user_id,
car_type=self.car_type,
facture__facture_id=1,
)
if len(cars) == 0:
cars = Car.objects.filter(
user_id=self.user_id,
car_type=self.car_type,
facture__facture_id=1,
)
但我不想重復所有的塊,我想知道是否有另一種方式:
Car.objects.filter(
user_id=self.user_id,
car_type=self.car_type,
facture__facture_id=1 | facture__facture_id='1',
)
uj5u.com熱心網友回復:
將 Q 物件用于“OR”邏輯(使用|運算子)(也在此處)
就像是
cars = Car.objects.filter(
user_id=self.user_id,
car_type=self.car_type,
).filter(
Q( facture__facture_id=1 ) | Q( facture__facture_id='1' )
)
(除了我不確定這種不確定性是如何產生的。它是 CharField 還是 IntegerField?我可以理解需要使用 Q 來處理 CharField 的變體)。
您還可以通過從另一個查詢集生成一個查詢集來大大減少重復代碼:
cars_base_qs = Car.objects.filter(
user_id=self.user_id,
car_type=self.car_type )
...
cars = cars_base_qs.filter( ...)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/424955.html
