1

I have the following model in my Django application; I want to get a queryset of my model with only one row for every unique value of a field (I do not care which row that would be at this point).

The problem is I cannot use the distinct function, because I am using annotations in my query.

Any idea how this could be achieved?

My model

class Slot(models.Model):
    # some other fields here
    start = models.DateTimeField()

Notes

Paris
  • 6,323
  • 7
  • 31
  • 49
  • Can you please add the annotation query that you're using? – Mehak Sep 19 '18 at 11:15
  • Sure thing! Slot.objects.annotate( pickup_count=Sum(Case( When(pickups__status='submitted', then=1), default=0, output_field=models.IntegerField(), )), ).filter( start__gt=timezone.now() + timedelta(days=1), ).order_by('start') – Paris Sep 19 '18 at 11:20
  • I don't think this is possible with pain Django ORM. However this is possible with using SQL. See - https://stackoverflow.com/questions/3800551/select-first-row-in-each-group-by-group – mylh Sep 19 '18 at 11:23
  • bro use SQL only...It more flex... – Mbambadev Sep 19 '18 at 11:40
  • Well, I've used annotate like this before in a similar query. I think this should work: Slot.objects.annotate( pickup_count=Sum(Case( When(pickups__status='submitted', then=1), default=0, output_field=models.IntegerField()))).filter( start__gt=timezone.now() + timedelta(days=1), ).order_by('distinct_field', 'start').distinct('distinct_field') – Mehak Sep 19 '18 at 12:32
  • You just need to pass the field that you want distinct as first field in order_by. Tell me if it works! – Mehak Sep 19 '18 at 12:34

0 Answers0