One-to-many relationship to multiple models
-
02-06-2021 - |
Вопрос
I have a model Thing
and a model Action
. There is a one-to-many relationship between Thing
s and Action
s. However, I would like to be able to subclass Action
to have (for example) BuildAction
, HealAction
and BloodyStupidAction
. Is it possible using Flask-SQLAlchemy to do this and maintain the single one-to-many relationship?
Решение
This problem is described in the SQLAlchemy docs under Inheritance Configuration. If your different subclasses will share the same database table, you should use single table inheritance.
Code example:
class Thing(db.Model):
__tablename__ = 'thing'
id = db.Column(db.Integer, primary_key=True)
actions = db.relationship('Action', backref=db.backref('thing'))
class Action(db.Model):
__tablename__ = 'action'
id = db.Column(db.Integer, primary_key=True)
thing_id = db.Column(db.Integer, db.ForeignKey('thing.id'))
discriminator = db.Column('type', db.String(50))
__mapper_args__ = {'polymorphic_on': discriminator}
class BuildAction(Action):
__mapper_args__ = {'polymorphic_identity': 'build_action'}
time_required = db.Column(db.Integer)
Each subclass of Action
should inherit the thing
relationship defined in the parent class. The action.type
column describes which subclass action each row of the table represents.
Не связан с StackOverflow