Created
October 23, 2013 09:25
-
-
Save sungmin-park/7115406 to your computer and use it in GitHub Desktop.
SQLAlchemy has wired problem of aliased.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
from sqlalchemy import Column, Integer, create_engine, case, func, String, cast | |
from sqlalchemy.ext.declarative import declarative_base | |
from sqlalchemy.orm import sessionmaker, aliased | |
engine = create_engine('sqlite://', echo=True) | |
Base = declarative_base() | |
class Number(Base): | |
__tablename__ = 'table' | |
id = Column(Integer, primary_key=True, autoincrement=True) | |
# set polymorphic | |
__mapper_args__ = {'polymorphic_on': id % 2} | |
class Even(Number): | |
__mapper_args__ = {'polymorphic_identity': 0} | |
class Odd(Number): | |
__mapper_args__ = {'polymorphic_identity': 1} | |
Base.metadata.create_all(engine) | |
Session = sessionmaker(bind=engine) | |
session = Session() | |
session.add(Number()) | |
session.add(Number()) | |
session.commit() | |
# without aliased | |
assert [i.id for i in session.query(Number).order_by(Number.id)] == [1, 2] | |
# aliased version | |
# this will raise sqlalchemy.exc.NoSuchColumnError: | |
# "Could not locate column in row for column 'table_1.id % :param_1'" | |
number_aliased = aliased(Number) | |
assert [ | |
i.id for i in session.query(number_aliased).order_by(number_aliased.id) | |
] == [1, 2] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment