[Answered ]-Combine rows on django queryset

1👍

You shouldn’t use aggregate() for this purpose, but annotate() (docs).

Input:

class T(models.Model):
    person = models.CharField(max_length=10)
    location = models.CharField(max_length=10)
    error = models.BooleanField()

T.objects.bulk_create([
    T(person='P1', location='L1', error=False),
    T(person='P1', location='L1', error=True),
    T(person='P2', location='L2', error=False),
    T(person='P2', location='L2', error=False)
])
for t in T.objects.all().values('person', 'location').distinct().annotate(error=Sum('error')):
    print(t)

Output:

{'person': 'P1', 'location': 'L1', 'error': True}
{'person': 'P2', 'location': 'L2', 'error': False}

0👍

Okay, so to help you out you can do this:

MyModel.objects.filter(your query).values('location', 'person').distinct()

by using .distinct() no duplicates will be present and you shall achieve what you want. (which also serves the purpose if location and person are the same for 2 rows)

Leave a comment