Flask-SQLAlchemy. Create several tables with all fields identical

Question:

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.

Asked By: Andrii Yurchuk

||

Answers:

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'
Answered By: Denis Otkidach
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.