Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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...

Thanks in advance.

EDIT with the solution based on answer

To use inheritence I had to change the entire structure to

class Group(Base):
   id = Column('id', Integer, primary_key=True)
   name  = Column('name',  String(80))
   group_type = Column('type', String(15))

    __mapper_args__ = {
        'polymorphic_on': g_type,
        'polymorphic_identity': 'Group'
    }

# Replacing Base => Group
class GroupA(Group):
   __mapper_args__ = {
      'polymorphic_identity': 'GroupA'
   }

class GroupB(Group):
   __mapper_args__ = {
      'polymorphic_identity': 'GroupB'
   }

And it's working, thank you very much !

like image 645
Ricky Levi Avatar asked Feb 08 '15 12:02

Ricky Levi


1 Answers

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

like image 191
tuomur Avatar answered Oct 20 '22 21:10

tuomur