Home > OS >  django find in field type json with value type int or str
django find in field type json with value type int or str

Time:02-17

I have a field type Json in a model, but I can't be sure if it's an integer or a string, the long version that works is:

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,
    )

But I want to do not repeat all the block, and I want to know if there is another way like:

Car.objects.filter(
   user_id=self.user_id,
   car_type=self.car_type,
   facture__facture_id=1 | facture__facture_id='1',
)

CodePudding user response:

Use Q objects for "OR" logic ( with | operator) (also here)

Something like

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' ) 
)

(except I am unsure how this uncertainty can arise. Is it a CharField or an IntegerField? I can understand needing to use Q to deal with variants of a CharField).

You can also greatly reduce duplicated code by generating one queryset from another:

cars_base_qs = Car.objects.filter(
    user_id=self.user_id,
    car_type=self.car_type )
...
cars = cars_base_qs.filter( ...)
  • Related