YardenST
YardenST

Reputation: 5256

Django ManyToMany Query OR Issue

I've got a problem for the following data:

Class Car:
    name = ...
    year_price_data = ManyToMany(YearPriceData)

Class YearPriceData:
    year = Integer
    min_price = Integer
    max_price Integer

So you can have this car for example:

Ford Focus:
---2014: 25,000$ - 40,000$
---2012: 7000$ - 23,000$

Now, I want to query all cars that match a certain year-price values:

for example: all cars that are sold in 2014 in the price range of 18,000-20,000$

(Should returns nothing in our example, yes?)

so this is the query ive made:

    Car.objects.filter(year_price_data__year=2014)

.filter(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))

The problem that because of the OR it returns the row of 2012, when it supposed to return nothing!

So my question is: how to make an OR query just for every manytomany row, so the query will be exact?

Upvotes: 1

Views: 53

Answers (1)

Daniel Roseman
Daniel Roseman

Reputation: 599490

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

Upvotes: 2

Related Questions