1

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)

2
  • If you use a ForeignKey toa Vendor model, then this is a lot easier. Commented Jul 29, 2020 at 19:18
  • unfortunately there is no Vendor model, the data for this table does not come from django Commented Jul 29, 2020 at 19:19

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.