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')
yieldsException Value: SELECT DISTINCT ON expressions must match initial ORDER BY expressions
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:
So after you'll have something like this: