This piece of code returns duplicates which are not database duplicates. This is, exact same records.
It could be fixed adding .distinct() after the order_by.
I tested it in the test deployment but I stashed (git stash save) the change to continue tomorrow.
@piotr.gawron if you want to see the change you can do git stash pop and reboot gunicorn.
Do you think the series of filters could be changed to avoid getting duplicates in the first place?
defget_exceeded_visits(user):returnVisit.objects.filter(datetime_end__lt=get_today_midnight_date(),is_finished=False,subject__default_location__in=get_filter_locations(user)).filter(# by default any visit where visit number is bigger than 1# or in case of first visit - visits that had some successful appointmentQ(visit_number__gt=1)|Q(appointment__status=Appointment.APPOINTMENT_STATUS_FINISHED)).filter(# visits that have scheduled appointments should be excluded~Q(appointment__status=Appointment.APPOINTMENT_STATUS_SCHEDULED)).order_by('datetime_begin')