Search code examples
pythonflasksqlalchemyflask-sqlalchemy

use_existing_column in flask sqlalchemy


I am using inheritance with Flask-SQLAlchemy on a class. The thing is that I have column conflicts because in some cases, I have two sub classes that have the same column name. For this I wanted to use the use_existing_parameter as suggested in https://docs.sqlalchemy.org/en/20/orm/inheritance.html and directly in the error i get in my code "use_existing_column parameter of mapped_column()".

But the problem is that db.Column (with db=SQLAlchemy() with from flask_sqlalchemy import SQLAlchemy, classic in a flask project) of sqlalchemy does NOT have this parameter.

How to do that then ? Cause I really don't understand how to avoid these problems without having to change the column names (and i dont want that)

Thanks in advance !

EDIT : For those who wonder, the SQLAlchemy class of Flask-SQLAlchemy is equivalent to SQLAlchemy.orm so you can use everything from it, including mapped_column instead of Column.


Solution

  • use a mapped_column()

    https://docs.sqlalchemy.org/en/20/orm/declarative_tables.html#declarative-table-with-mapped-column

    class Automobile(Base):
    
         __tablename__ = 'automobiles'
    
         id = Column(Integer, primary_key=True)
         name = Column(String, nullable=False)
    
    
    class Truck(Automobile):
    
         name = mapped_column(String, nullable=False, use_existing_column=True)