I have a querset with attributes location, person and error
I need to either create a new queryset or edit an existing one such that rows are "combined" based on a certain criteria This criteria is if the location and person are the same Once combined, I want to make the error value be true if any of the rows that are being combined had a true value In this case the table should be changed as follows:
Location | Person | Error |
---|---|---|
L1 | P1 | false |
L1 | P1 | true |
L2 | P2 | false |
L2 | P2 | false |
Location | Person | Error |
---|---|---|
L1 | P1 | true |
L2 | P2 | false |
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}
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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.