Django QuerySet 基于字段值聚合

Django QuerySet aggregate based on field value

我的模型如下:

class AssetIdentifications(models.Model):  
    id = models.BigIntegerField(primary_key=True, db_index=True, editable=False, null=False)
    entity = models.ForeignKey(
        "Entity", db_constraint=False, null=False,
    )
    asset = models.ForeignKey(
        "Asset", db_constraint=False, null=False
    )
    type = models.CharField(
        max_length=32,
        null=False,
    )
    vendor = models.CharField(
        max_length=64, null=False
    )
    software = models.CharField(
        max_length=64, null=False
    )
    version = models.CharField(
        max_length=64, null=False
    )

我想获得一个基于 vendor 的唯一值分组的查询集。结果应如下所示:

{"vendor1": [\<list of AssetIdentifications\>], "vendor2": [\<list of AssetIdentifications\>] ...}

这是否可以通过 group_byaggregate 函数实现(我在文档中没有找到类似的东西)?或者我是否必须遍历通过像 AssetIdentifications.objects.filter(entity=e)

这样的过滤获得的查询集

您可以使用 groupby(…) function of the itertools module:

from itertools import groupby
from operator import attrgetter

result = {
    k: list(vs)
    for k, vs in
    groupby(AssetIdentifications.objects.order_by('vendor'), attrgetter('vendor'))
}

此处 result 是一个将 vendor 映射到 AssetIndentification 对象列表中的字典。