1

I would like to have a model class that inherits from 2 other model classes. Here is something that should work but it doesnt.

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 = db.Column(db.Integer, primary_key=True)

class A(BaseModel):
    a_name = db.Column(db.String)
    a_type = db.Column(db.String)
    __mapper_args__ = {
        'polymorphic_on': a_type,
        'polymorphic_identity': 'a',
    }

class B(BaseModel):
    b_name = db.Column(db.String)
    b_type = db.Column(db.String)
    __mapper_args__ = {
        'polymorphic_identity': 'b',
        'polymorphic_on': b_type
    }

class Inheritance(A, B):
    a_id = db.Column(db.ForeignKey(A.id), primary_key=True)
    b_id = db.Column(db.ForeignKey(B.id), primary_key=True)
    name = db.Column(db.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()

I got this error

sqlalchemy.exc.InvalidRequestError: Class <class '__main__.Inheritance'> has multiple mapped bases: [<class '__main__.A'>, <class '__main__.B'>]

What is wrong? I understand what the error says, but I dont know how to fix it.

Can anyone give me a minimal but fully working example of how to set it up?

1 Answer 1

2

In general in SQLAlchemy you can not inherit from a class that is not __ abstract__, you can either make A and B abstract, but then you are not going to use them in your database directly

The best option is to make two new classes ABase, BBase with __ abstract__=Tue, and them inherit them both A,B and the "Inheritance" class.

Sign up to request clarification or add additional context in comments.

1 Comment

hmm, interesting... i will try and let you know it it works the way I need. Thanx

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.