django 在字段类型 json 中查找值类型为 int 或 str
django find in field type json with value type int or str
我在模型中有一个字段类型 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',
)
使用Q objects for "OR" logic ( with |
operator) (also here)
类似
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( ...)
我在模型中有一个字段类型 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',
)
使用Q objects for "OR" logic ( with |
operator) (also here)
类似
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( ...)