Brent
Brent

Reputation: 173

Django Querying Relation of Relation

I'm stuck on a Django ORM issue that is bugging me. I have a set of models linked by a foreign key but the requirements are a bit odd. I need to list items by their relation's relation. This is hard to explain so I've tried to depict this below, given:

Work

Award

AwardCategory

I need to list work items so they are listed by the award category. Desired output would be:

Work Instance A

Work Instance A (same instance as above, but listed by different award__category)

Work Instance B

Essentially I want to list all work by the award category. I can get this to work in part but my solution is filthy and gross. I'm wondering if there is a better way. I considered using a ManyToMany and a through attribute but I'm not certain if I'm utilizing it correctly.

Upvotes: 0

Views: 115

Answers (2)

Brent
Brent

Reputation: 173

So I came up with a similar result but it still feels a little dirty :(

categories = AwardCategory.objects.all()
work = []
for cat in categories:
    work_in_cat = Work.objects.filter(awards__category=cat).distinct()
    for w in work_in_cat:
        work.append({
            'work': w,
            'category': cat,
            'awards': w.awards.filter(category=cat)
        })

This produces the results I want but it seems so wrong to be doing this in a for loop!

Upvotes: 0

Burhan Khalid
Burhan Khalid

Reputation: 174614

Adjust the following as per your model's fields and relations:

for w in Work.objects.all():
    print w
    for award in w.award_set.order_by(awardcategory):
         print "%s that belongs to %s" % (award,award.awardcategory)

Upvotes: 1

Related Questions