Django related _set with order_by showing duplicates

541 views Asked by At

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 duplicates
  • driver.car_set.order_by('model__market_date').distinct('model__market_date') causes duplicates
  • driver.car_set.order_by('model__market_date').distinct('pk') yields Exception Value: SELECT DISTINCT ON expressions must match initial ORDER BY expressions
1

There are 1 answers

3
e-coeur On

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]