Reputation: 316
Let's say I have the following table called my_table
id | type |
---|---|
1 | a |
2 | b |
3 | b |
4 | a |
I want to have two models that rely on the same table, but when I query each they will return only results with a default filter on type
column.
So for example -
def filter_by_a():
...
def filter_by_b():
...
class ModelA(db.Model):
__tablename__ = 'my_table'
default_filter = filter_by_a
id = db.Column(db.Integer, primary_key=True)
type = db.Column(db.String)
class ModelB(db.Model):
__tablename__ = 'my_table'
default_filter = filter_by_b
id = db.Column(db.Integer, primary_key=True)
type = db.Column(db.String)
When I use db.session.query(ModelA)
the results are
id | type |
---|---|
1 | a |
4 | a |
And when I use db.session.query(ModelB)
the results are
id | type |
---|---|
2 | b |
3 | b |
Is there a way to do that?
Upvotes: 0
Views: 806
Reputation: 316
https://docs.sqlalchemy.org/en/14/orm/inheritance.html#single-table-inheritance
class MyTableModel(db.Model):
__tablename__ = 'my_table'
id = db.Column(db.Integer, primary_key=True)
type = db.Column(db.String)
__mapper_args__ = {
'polymorphic_on': type
}
class ModelA(MyTableModel):
__mapper_args__ = {
'polymorphic_identity': 'a'
}
class ModelB(MyTableModel):
__mapper_args__ = {
'polymorphic_identity': 'b'
}
Upvotes: 1