Reputation: 18711
With Django 1.7, using following code in my view:
driver = get_object_or_404(Driver, id=self.object.id)
cars = driver.car_set.order_by('model__market_date')
for car in cars: # for testing only
print car.id # outputs e.g. 3, 3, 3, 5
When I try this, I get duplicate results for cars (e.g. twice car #3), dependent on the amount of models. I don't want this.
However, when I use cars = driver.car_set.all()
, the duplicate results are not there. But I want my car list to be sorted on market_date
.
Any pointer on how to fix this? I tried with aggregate() and distinct() but that didn't fix the situation unfortunately (or I'm doing something wrong).
My tries with distinct()
:
driver.car_set.order_by('model__market_date').distinct()
causes duplicatesdriver.car_set.order_by('model__market_date').distinct('model__market_date')
causes duplicatesdriver.car_set.order_by('model__market_date').distinct('pk')
yields Exception Value: SELECT DISTINCT ON expressions must match initial ORDER BY expressions
Upvotes: 0
Views: 545
Reputation: 75
I don't know why do you receive duplicate results, because i don't see nothing unnatural in your code. In case if you want just to receive a list of cars id (without duplicates), you can change your for cycle in this way:
cars_id = [] # creating empty list for cars id with duplicates
for car in cars: # for cycle
cars_id.append(car.id) # appends numbers 3, 3, 3, 5 to our list
cars_id = list(set(cars_id)) # making list with unique values using built-in function set()
So after you'll have something like this:
>>> cars_id
... [3, 5]
Upvotes: 1