Q:

Django QuerySet aggregate based on field value

My model is as follows:
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
    )

I want to get a queryset that is grouped based on unique values of vendor.  The result should look something like this:
{"vendor1": [\<list of AssetIdentifications\>], "vendor2": [\<list of AssetIdentifications\>] ...}

Is this possible with a group_by or aggregate function (I haven't found something like this in the docs)?  Or would I have to iterate through the queryset I obtain just through filtering like AssetIdentifications.objects.filter(entity=e)

A:

You can use the 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'))
}
Here result is a dictionary that maps the vendors on a list of AssetIndentification objects.