Drakekin
Drakekin

Reputation: 1348

One-to-many relationship to multiple models

I have a model Thing and a model Action. There is a one-to-many relationship between Things and Actions. 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?

Upvotes: 2

Views: 1310

Answers (1)

robots.jpg
robots.jpg

Reputation: 5161

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.

Upvotes: 2

Related Questions