[Answer]-Django Querying Relation of Relation

1👍

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)

0👍

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!

👤Brent

Leave a comment