I'm using declarative_base() and trying to figure out how to enforce a lazy inner join when using a many-to-many relationship.
I have tables in MySQL and InnoDB with Foreign key constraints defined.
users: userid, name
permissions: permissionid, name
users_permissions: userid, permissionid
I'm using metadata.reflect()
to load my database.
class User_Perm(Base):
__table__ = Base.metadata.tables['users_permissions']
class User(Base):
__table__ = Base.metadata.tables['users']
permissions = orm.relationship('Permission',
secondary=User_Perm.__table__,
order_by='Perm.name',
innerjoin=True,
lazy=True,
)
class Permission(Base):
__table__ = Base.metadata.tables['permissions']
Whenever I select
u = Session().query(User).filter(User.name == 'myuser').first()
u.permissions
The query received by MySQL server is:
SELECT permissions.permissionid AS permissions_permissionid,
permissions.name AS permissions_name
FROM permissions, users_permissions
WHERE ? = users_permissions.userid
AND permissions.permissionid = users_permissions.permissionid
ORDER BY permissions.name
As we can see, the FROM permissions, users_permissions
is not an inner join. Can I force this without the need to use lazy=False
because if I do so, the cascading effect will be to load too much information as permissions
are also in relationship with another table (not mentioned in example) and users
is also related to other tables (again, not mentioned in example). I would like to use the same template for relationship for all my classes.
EDIT: CONTEXT I'm trying to replicate all the SQL queries to match those from the current system. I'm trying to migrate from oursql
to sqlalchemy orm
.