简体   繁体   English

Django过滤器基于多个条件在order_by之后返回重复项

[英]Django filter returning duplicates after order_by based on multiple criteria

I'm having difficulty returning unique Clazz objects based off my criteria and ordering. 我很难根据我的标准和顺序返回唯一的Clazz对象。 Clazz and Session are two separate models and a class can have many sessions. ClazzSession是两个单独的模型,一个类可以有多个会话。

Once I introduced the order_by I'm seeing duplicate Clazz objects. 一旦介绍了order_by我就会看到重复的Clazz对象。 How can I remove the duplicates? 如何删除重复项? A simple distinct() doesn't seem to work. 一个简单的distinct()似乎不起作用。

classes = Clazz.objects.filter(location=loc).distinct().order_by('session__start_date', 'session__end_date')

I guess you can do something like this: 我想你可以做这样的事情:

classes = Clazz.objects.filter(location=loc).annotate(
        startdate=Max('session__start_date'),
        end_date=Max('session__end_date')
    ).order_by('startdate', 'end_date')

After @Alasdair's response, ended up just doing this: 在@Alasdair的回应之后,最终只是这样做:

dup_list = []
class_list = []
for c in classes:
    if c not in dup_list:
        dup_list.append(c)
        class_list.append(c)
classes = class_list

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM