I have a Django data model like this (data fields omitted):
class Atom(Model):
pass
class State(Model):
atom = ForeignKey(Atom)
class Transition(Model):
atom = ForeignKey(Atom)
upstate = ForeignKey(State,related_name='uptrans')
lostate = ForeignKey(State,related_name='lotrans')
When I query, the fields to be restricted can be in either model, so it is easiest to query on Transition.objects.filter(...)
since all fields in the other models can be reached through the foreign keys. Let's call the resulting QuerySet t
.
Now what I want in addition is a QuerySet a
of the Atom model that corresponds to t
, which can be done like a = t.values('atom').distinct()
. So far so good.
However, I also want each of the entries in a
to have one attribute/field that holds the QuerySet for the States of this Atom, still reflecting the criteria on the original selection t
, through either one of the upstate
or lostate
ForeignKeys.
I have created my QuerySet on States up to now by looping over t
, adding the values('upstate_id')
and values('lostate_id')
to a Python set()
for throwing out duplicates, and then querying States with this list. But then I cannot achieve the nested structure of States within Atoms.
Any suggestions on how to do this are welcome, if possible with unevaluated QuerySet
s, since I pass them not into a template but a generator (yield
statements), which is a nice way of streaming large amounts of data.