我试图基于m2m字段执行order_by,但它最终在我的查询集中创建重复的条目.我一直在搜索关于堆栈交换的
django文档和相关问题,但我还没有能够提出任何解决方案.
楷模:
class WorkOrder(models.Model):
...
appointment = models.ManyToManyField(Appointment, null=True, blank=True, related_name = 'appointment_from_schedule')
...
class Appointment(models.Model):
title = models.CharField(max_length=1000, blank=True)
allDay = models.BooleanField(default=False)
start = models.DateTimeField()
end = models.DateTimeField(null=True, blank=True)
url = models.URLField(blank=True, null=True)
查询:
qs = WorkOrder.objects.filter(work_order_status="complete").order_by("-appointment__start")
结果:
[<WorkOrder: 45: Davis>, <WorkOrder: 45: Davis>]
在交互模式下:
>>>qs[0] == a[1]
True
>>>qs[0].pk
45
>>>qs[1].pk
45
如果我删除order_by,那么我只得到一个结果,但稍后添加它会将重复的条目放回去.
>>>qs = WorkOrder.objects.filter(work_order_status="complete")
>>>qs
[<WorkOrder: 45: Davis>]
>>>qs.order_by('appointment__start')
[<WorkOrder: 45: Davis>, <WorkOrder: 45: Davis>]
我尝试添加.distinct()和.distinct(‘pk’),但前者没有效果,后者导致错误:
ProgrammingError: SELECT DISTINCT ON expressions must match initial ORDER BY expressions
最佳答案 您可以尝试使用值注释:
qs = WorkOrder.objects.filter(work_order_status="complete").values("appointment").annotate(status="work_order_status").order_by("-appointment__start")