Suppose we have a PostgreSQL database with two tables A, B.
table A columns: id, name table B columns: id, name, array_a
The column array_a in table B contains a variable length array of ids from table A. In SQLAlchemy we have two classes that model those tables, say class A and B.
The following works fine to get all the objects A that are referenced in an object B:
session.query(A).join(B, A.id == func.any(B.array_a)).filter(B.id == <id>).all()
How can we create a relationship in B referencing the objects A corresponding to the array? Tried column comparators using the func.any above but it complains that ANY(array_a) is not a column in the model. Specifying the primaryjoin conditions as above doesn’t seem to cut it either.
This anti-pattern is called “Jaywalking”; and PostgreSQL’s powerful type system makes it very tempting. you should be using another table:
Which is mapped:
example:
If you are stuck with the
ARRAYcolumn, your best bet is to use an alternate selectable that “looks” like a proper association table.which gives you:
And obviously, since there’s no real table there,
viewonly=Trueis neccesary and you can’t get the nice, dynamic objecty goodness you would if you had avoided jaywalking.