I am having issues using SQLAlchemy. When executing below code I get an error (1066, "Not unique table/alias: 'user_role'")
. If I am to execute the query myself in mysql-console taken from the sqlalchmey query-string I get no such error. What could make sqlachemy make it so that it throws an error such as this?
UserRole is table user_role.
@classmethod def get_stud_no_edu_route(cls, cur_user): query = cur_user.db.query(User) .join(UserRole, User.id == UserRole.user_id) .join(School, UserRole.school_id == School.id) .filter((UserRole.role == Role.STUDENT) & (User.educational_route == None) & (School.name.like('%gymnas%'))) query = User.apply_dashboard_permission(query, cur_user) return query
Raw mysql:
SELECT user.id AS user_id, user.active AS user_active, user.was_activated AS user_was_activated, user.archived AS user_archived, user.hidden_photo AS user_hidden_photo, user.first_name AS user_first_name, user.last_name AS user_last_name, user.full_name AS user_full_name FROM user INNER JOIN user_role ON user.id = user_role.user_id INNER JOIN school ON user_role.school_id = school.id WHERE user_role.`role` = 'Student' AND user.educational_route IS NULL AND school.name LIKE '%gymnas%';
Advertisement
Answer
For some reason the issue wasn’t user_role but school instead. After opening the project the day after, the error issue was for ‘school’ and not ‘user_role’.
I tried adding stud_roles = orm.aliased(UserRole)
before but to no avail. By adding schools = orm.aliased(School)
as well my issue was resolved.
I read that every table that is in a select-query needs to be in aliased. Not 100% on why but it solved my issue.