Django Querying Relation of Relation

Posted by Brent on Stack Overflow See other posts from Stack Overflow or by Brent
Published on 2012-09-13T19:20:09Z Indexed on 2012/09/13 21:38 UTC
Read the original article Hit count: 428

Filed under:
|
|
|

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

  • ManyToMany(Award)

Award

  • ForeignKey(AwardCategory)

AwardCategory

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

Work Instance A

  • Award Instance A that belongs to Award Category Instance A
  • Award Instance C that belongs to Award Category Instance A
  • Award Instance G that belongs to Award Category Instance A

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

  • Award Instance F that belongs to Award Category Instance B
  • Award Instance R that belongs to Award Category Instance B
  • Award Instance Z that belongs to Award Category Instance B

Work Instance B

  • Award Instance B that belongs to Award Category Instance A
  • Award Instance A that belongs to Award Category Instance A

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.

© Stack Overflow or respective owner

Related posts about django

Related posts about orm