buhutz
buhutz

Reputation: 33

SQLAlchemy Polymorphic Loading

I've this model in SQLAlchemy:

class User(Base):
    __tablename = 'users'
    id = Column(Integer, primary_key=True, autoincrement=True)
    type = Column(Text, nullable=False)
    user_name = Column(Text, unique=True, nullable=False)
    __mapper_args__ = {'polymorphic_on': type}

class Client(User):
    __tablename__ = 'clients'
    __mapper_args__ = {'polymorphic_identity': 'client'}
    id = Column(Integer, ForeignKey('users.id'), primary_key=True)
    client_notes = Column(Text)

This is a joined table inheritance. The problem is when I'm querying User:

self.session.query(User).all()

all I get is records from clients, while what I want is all record on User without Client. How do I solve this problem?

Edit: I'm using SQLAlchemy 0.7.4 and Pyramid 1.3a3

Upvotes: 3

Views: 1439

Answers (1)

van
van

Reputation: 76982

session.query(User) does not perform any filtering based on the value of type column.
However, the SQL SELECT statement it generates selects only data from the users table (unless with_polymorphic(...) is used).

But you can add the filter explicitely to achive the desired result:

session.query(User).filter(User.type=='user').all()

Upvotes: 2

Related Questions