[英]Django related _set with order_by showing duplicates
With Django 1.7, using following code in my view: 在Django 1.7中,在我看来使用以下代码:
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 (eg twice car #3), dependent on the amount of models. 当我尝试这种方法时,我会根据模型的数量获得重复的汽车结果(例如两次3号汽车)。 I don't want this.
我不要这个
However, when I use cars = driver.car_set.all()
, the duplicate results are not there. 但是,当我使用
cars = driver.car_set.all()
,没有重复的结果。 But I want my car list to be sorted on market_date
. 但是我希望我的汽车清单在
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).
我尝试使用aggregate()和distinct(),但是不幸的是,这种方法不能解决问题(或者我做错了事)。
My tries with distinct()
: 我的尝试与
distinct()
:
driver.car_set.order_by('model__market_date').distinct()
causes duplicates driver.car_set.order_by('model__market_date').distinct()
导致重复 driver.car_set.order_by('model__market_date').distinct('model__market_date')
causes duplicates driver.car_set.order_by('model__market_date').distinct('model__market_date')
导致重复 driver.car_set.order_by('model__market_date').distinct('pk')
yields Exception Value: SELECT DISTINCT ON expressions must match initial ORDER BY expressions
driver.car_set.order_by('model__market_date').distinct('pk')
产生Exception 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:
如果您只想接收汽车ID列表(无重复),则可以通过以下方式更改for周期:
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]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.