Anmol Porwal
Anmol Porwal

Reputation: 15

SQLAlchemy: querying on all subclasses of a class

I have the following code in which two classes inherit from a common parent class (which is not a table). I want to query on parent name so that it will also query in all the subclasses and give a result.

class Parent(Base):
    __abstract__ = True

    id = Column(Integer, primary_key=True)
    name = Column(String, unique=True)
    type = Column(String)

    def __init__(self, name, type):
        self.name = name
        self.type = type

class Child(Parent):
    __tablename__ = "child"

    directory = Column(String, default="/bin")
    prefix = Column(String, default="child_prefix")

class ChildOne(Parent):
    __tablename__ = "child_one"

    directory = Column(String, default="/dev")
    mode = Column(Boolean, default=1)
    bool = Column(Boolean, default=0)

I tried session.query(Parent).filter(Parent.name == name).one()
but since Parent is not a table its throwing an error.
Is there any way to do it other than separately querying all the sub classes?

Upvotes: 0

Views: 1444

Answers (1)

Jason Russell
Jason Russell

Reputation: 1236

You can use something like joined table inheritance:

http://docs.sqlalchemy.org/en/latest/orm/inheritance.html#joined-table-inheritance

Upvotes: 1

Related Questions