我的模型如下: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_bya or函数是否可行aggregate(我在文档中没有找到类似的东西)?或者我是否必须遍历我通过过滤获得的查询集AssetIdentifications.objects.filter(entity=e)
1 回答
斯蒂芬大帝
TA贡献1827条经验 获得超8个赞
您可以使用模块的groupby(…)
功能:itertools
from itertools import groupby
from operator import attrgetter
result = {
k: list(vs)
for k, vs in
groupby(AssetIdentifications.objects.order_by('vendor'), attrgetter('vendor'))
}
这是一个将s 映射到对象列表的result字典。vendorAssetIndentification
添加回答
举报
0/150
提交
取消