简体   繁体   English

合并 django 查询集上的行

[英]Combine rows on django queryset

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 L1 P1 P1 false错误的
L1 L1 P1 P1 true真的
L2 L2 P2 P2 false错误的
L2 L2 P2 P2 false错误的
Location地点 Person Error错误
L1 L1 P1 P1 true真的
L2 L2 P2 P2 false错误的

You shouldn't use aggregate() for this purpose, but annotate() ( docs ).您不应为此目的使用aggregate() ,而应使用annotate()文档)。

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: 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.通过 using.distinct() 不会出现重复项,您将实现您想要的。 (which also serves the purpose if location and person are the same for 2 rows) (如果 location 和 person 对于 2 行相同,这也可以达到目的)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM