[Answered ]-Django ManyToMany Query OR Issue

2👍

Firstly, I don’t see why you want a ManyToMany relationship here. Although a car can have many yearpricedata instances, each yearpricedata only relates to one car. So the proper relationship is a ForeignKey from YearPriceData to Car.

Either way, you should read the documentation on spanning multi-valued relationships. As explained there, in order for the two conditions to be both applied on the same entities, you need to have them in the same filter call. This should work:

Car.objects.filter(year_price_data__year=2014, Q(year_price_data__min_price__lte=20000,year_price_data__min_price__gte=18000) | Q(year_price_data__max_price__lte = 20000,year_price_data__max_price__gte=18000))

Leave a comment