私のモデルは次のとおりです。
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_by
oraggregate
関数で可能ですか(ドキュメントでこのようなものは見つかりませんでした)?または、次のようにフィルタリングするだけで取得したクエリセットを反復処理する必要がありますか?AssetIdentifications.objects.filter(entity=e)
モジュールの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'))
}
これresult
は、オブジェクトのvendor
リストにをマップする辞書AssetIndentification
です。
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加