I am attempting to perform an order_by based a m2m field, but it ends up creating duplicate entries in my queryset. I have been searching through the django documentation and related questions on stack exchange, but I haven't been able to come up with any solutions.
Models:
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)
Query:
qs = WorkOrder.objects.filter(work_order_status="complete").order_by("-appointment__start")
Results:
[<WorkOrder: 45: Davis>, <WorkOrder: 45: Davis>]
In interactive mode:
>>>qs[0] == a[1]
True
>>>qs[0].pk
45
>>>qs[1].pk
45
If I remove the order_by then I get only a single result, but adding it later puts the duplicate entry back in.
>>>qs = WorkOrder.objects.filter(work_order_status="complete")
>>>qs
[<WorkOrder: 45: Davis>]
>>>qs.order_by('appointment__start')
[<WorkOrder: 45: Davis>, <WorkOrder: 45: Davis>]
I have tried adding .distinct() and .distinct('pk'), but the former has no effect and the latter results in an error:
ProgrammingError: SELECT DISTINCT ON expressions must match initial ORDER BY expressions
order_by
, I want to sorting book base on author name like this book__author__name, but this appear the duplicate record. How to I do with annotate, thank you ! – Sabotage