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:
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.
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 !
Single Table Inheritance is what you need. Define your group_type
as the polymorphic identity and you're all set.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With