"Expanding" a reflexive Many to Many relationship in SQLAlchemy

240 views Asked by At

Using Elixir 0.7.1 and SQLAlchemy 0.7.8, I've created a model having a many-to-many relationship back to itself, which looks like:

from elixir import *

class MyModel(Entity):
    name = Field(Unicode(30))
    related = ManyToMany('MyModel')

Now, if I have some arbitrary query on these, say

q1 = MyModel.query.filter(MyModel.name.like("%Bob%"))

Then I want to build a separate query that will return the flat list of distinct MyModel objects that are related to any of the objects in q1. That is, if I had

q1.all() == [m1, m2, m3]

Then I want a query q2 (probably with q1 as a subquery) which will return a flat list consisting of the union of m1.related, m2.related, and m3.related. This is easy to do if I just execute q1 first and then drop down to Python list manipulation for the rest, but it seems like there should be a faster way when q1 returns many objects. Any thoughts on how to do this? Should I be using some sort of join on/with the intermediary table generated by Elixir for the many-to-many relationship?

Thanks!

1

There are 1 answers

0
Tim Kunisky On

Looks like there is a simple solution without having to explicitly reference the join table:

q2 = MyModel.query.join(q1.subquery(), MyModel.related)