I'm using Flask-SQLAlchemy==2.2 and have STI (Single Table Inheritance) configuration like this:
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
class Item(db.Model):
__tablename__ = 'item'
id = db.Column(db.Integer, primary_key=True)
info = db.Column(db.String(255))
type = db.Column(db.String())
__mapper_args__ = {
'polymorphic_on': type
}
class ItemA(Item):
__mapper_args__ = {
'polymorphic_identity': 'a'
}
class ItemB(Item):
__mapper_args__ = {
'polymorphic_identity': 'b'
}
class ItemC(Item):
__mapper_args__ = {
'polymorphic_identity': 'c'
}
And I want to query items of a particular kind. I can do it like this:
Item.query.filter_by(type='b').all()
Is there any chance to do it like the following?
ItemB.query.all()
Thanks.
It's not working because you are accidentally using joined table inheritance instead. flask-sqlalchemy automatically sets __tablename__
for you. You need to explicitly set it to None
if you want single table inheritance:
class ItemB(Item):
__tablename__ = None
__mapper_args__ = {
'polymorphic_identity': 'b'
}