Multiple Inheritance of Joined Table Inheritance in Flask-Sqlalchemy
I' like to define a model which inheritance from two base models in flask-sqlalchemy as follows:
class BaseModel(db.Model):
id = db.Column(db.Integer(). primary_key=1)
class BaseModelA(BaseModel):
base_model_a_field = db.Column(db.String(9))
base_model_a_type = db.Column(db.String(9))
__mapper_args__ = {"polymorphic_identity": "a", "polymorphic_on": base_model_a_type}
class BaseModelB(BaseModel):
base_model_b_field = db.Column(db.String(9))
base_model_b_type = db.Column(db.String(9))
__mapper_args__ = {"polymorphic_identity": "b", "polymorphic_on": base_model_b_type}
class InheritancedModel(BaseModelA, BaseModelB):
model_a_id = db.Column(db.Integer(), db.ForeignKey("base_model_a.id"), primary_key=1)
model_b_id = db.Column(db.Integer(), db.ForeignKey("base_model_b.id"), primary_key=1)
other_field = db.Column(db.String(9))
When create the instance of InheritancedModel,
IntegrityError: (_mysql_exceptions.IntegrityError) (1452, 'Cannot add or update a child row: a foreign key constraint fails happens.
Can i do multiple inheritance of joined table inheritance in flask-sqlalchemy?
Can you do this in regular SQLAlchemy?
I can't reproduce your issue. If you are having issues with your own code, please use Stack Overflow. Be sure to include a Minimal, Complete, and Verifiable Example.
import sqlalchemy as sa
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SQLALCHEMY_ECHO'] = True
db = SQLAlchemy(app)
class BaseModel(db.Model):
__abstract__ = True
id = sa.Column(sa.Integer, primary_key=True)
class A(BaseModel):
a_name = sa.Column(sa.String)
a_type = sa.Column(sa.String)
__mapper_args__ = {
'polymorphic_on': a_type,
'polymorphic_identity': 'a',
}
class B(BaseModel):
b_name = sa.Column(sa.String)
b_type = sa.Column(sa.String)
__mapper_args__ = {
'polymorphic_identity': 'b',
'polymorphic_on': b_type
}
class Inheritance(A, B):
a_id = sa.Column(sa.ForeignKey(A.id), primary_key=True)
b_id = sa.Column(sa.ForeignKey(B.id), primary_key=True)
name = sa.Column(sa.String)
db.create_all()
db.session.add_all((A(), B()))
db.session.commit()
db.session.add(Inheritance(a_id=1, b_id=1))
db.session.commit()
@davidism Thanks for your example. I think it might be table create sequence of Flask-Migrate.