我的模型如下: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。結(jié)果應(yīng)該是這個樣子:{"vendor1": [\<list of AssetIdentifications\>], "vendor2": [\<list of AssetIdentifications\>] ...}group_bya or函數(shù)是否可行aggregate(我在文檔中沒有找到類似的東西)?或者我是否必須遍歷我通過過濾獲得的查詢集AssetIdentifications.objects.filter(entity=e)
1 回答

斯蒂芬大帝
TA貢獻(xiàn)1827條經(jīng)驗 獲得超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
提交
取消