Andrii Yurchuk
Andrii Yurchuk

Reputation: 3280

Flask-SQLAlchemy. Create several tables with all fields identical

I'm using Flask with its SQLAlchemy extension. I need to define several model classes, which will create tables in MySQL database. The tables will only differ by name, all the field names/datatypes in them will be identical. How do I define the classes for all those tables? I'm thinking of some inheritance, but I'm not quite sure how exactly would I do that.

Upvotes: 1

Views: 1543

Answers (1)

Denis Otkidach
Denis Otkidach

Reputation: 33250

Just define all your columns in a mix-in class:

from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()

class MyMixin(object):
    id =  Column(Integer, primary_key=True)
    data = Column(String)

class MyModel1(MyMixin, Base):
    __tablename__ = 'models1'

class MyModel2(MyMixin, Base):
    __tablename__ = 'models2'

Upvotes: 8

Related Questions