Nested QuerySets in Django

I have a Django data model similar to 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 request, the fields that need to be limited can be in any model, so the easiest way to request is Transition.objects.filter(...), since all fields in other models can be accessed through foreign keys. Let me call the resulting QuerySet t.

Now I want to add a QuerySet to aan Atom model that matches twhat can be done like a = t.values('atom').distinct(). So far so good.

However, I also want each of the entries in to ahave one attribute / field that contains a QuerySet for the states of this atom, still reflecting the criteria for the original selection t, through one of upstateor lostateForeignKeys.

QuerySet , t, values('upstate_id') values('lostate_id') Python set() . .

, , , , QuerySet s, , (yield), .

+5
2

, , , , QuerySet .

def getAtomsWithStates(t):
    atom_ids = set( t.values_list('atom_id',flat=True) )
    atoms = Atoms.objects.filter(pk__in=atom_ids)
    for atom in atoms:
        upstate_ids = t.filter(atom=atom).values_list('upstate_id',flat=True)
        lostate_ids = t.filter(atom=atom).values_list('lostate_id',flat=True)
        all_ids = set( upstate_ids + lostate_ids )

        # attach the new QuerySet to the entry in the outer one:
        atom.States = State.objects.filter(pk__in=all_ids)

    return atoms

, :

someAtoms = getAtomsWithStates( Transition.objects.filter(...) )
for atom in someAtoms:
    for state in atom.States:
        print state.field

, , , .

+2

, set s. SQL In . . : " , : (1, 2, 3, 3, 3, 4)," 1, 2, 3 4. Python set, . set, .

:

states = State.objects.filter(
    Q(pk__in=t.values_list('upstate', flat=True)) |
    Q(pk__in=t.values_list('lostate', flat=True)
)

, , , , . , . Q , , , . M2M . ? atom Transition atom State :

atoms = Atom.objects.filter(
    pk__in=State.objects.filter(
        Q(pk__in=t.values_list('upstate', flat=True)) |
        Q(pk__in=t.values_list('lostate', flat=True)
    ).values_list('atom', flat=True)
)
0