我正在尝试基于 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