pythonsqlalchemy

SQLAlchemy how to define two models for the same table


I have a single table, and one of the columns is a varchar with two values ('groupA','groupB')

When I created my models I wanted to achieve two things:

  1. model for groupA - that hold X amount of related functions
  2. model for groupB - that hold Y amount of related functions

the functions are not the same for both models, though they represents the same table:

class GroupA(Base):
  __tablename__ = 'groups' 

  id = Column('id', Integer, primary_key=True)
  name  = Column('name',  String(80))
  group_type = Column('type', String(15), default="groupA")

And for groupB:

class GroupB(Base):
  __tablename__ = 'groups' 

  id = Column('id', Integer, primary_key=True)
  name  = Column('name',  String(80))
  group_type = Column('type', String(15), default="groupB")

So GroupA & B are the same table: "groups", but GroupA has 100 rows, groupB has 20rows

I want to prevent writing this all the time:

session.query(GroupA).filter(group_type = 'groupA')
session.query(GroupB).filter(group_type = 'groupB')

How can I configure my model with some kind of a "fitler" that when I'll query.all() it will return the data relavent for each model ? right now I receive all data in both models no matter which model I queried...


Solution

  • Single Table Inheritance is what you need. Define your group_type as the polymorphic identity and you're all set.