'Django ORM filter with two __in
I'm having model with two field. product_ids_list = [1,2,3,4] selling_prices_list = [65, 89, 93] And length of product_ids_list and selling_prices_list are same.
I'm able to perform below ORM filter for one product_id and it's corresponding selling price like this.
product_instances = Product.objects.filter(product_id=product_ids_list[0], selling_price=selling_prices_list[0]).first()
But how to do perform ORM filter with just one DB call with product_ids_list and it's corresponding selling_prices_list.
product_instances = Product.objects.filter(product_id__in=product_ids_list, selling_price__in=selling_prices_list).first() (This isn't working in the expected way)
Solution 1:[1]
If product_id is ForeignKey and selling_price is IntegerField then the filter code would be:
product_instances = Product.objects.filter(product_id__id__in=product_ids_list, selling_price__in=selling_prices_list).first()
As you are supplying list of IDs, we would have to compare product IDs. If we filter with product_id__in, it compares Product object with IDs in the list.
Suggesstion: It would be better to have ForeignKey field name as product instead of product_id to avoid confusion like the above ORM filter.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Aadarsha |
