问题
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.
回答1:
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'
来源:https://stackoverflow.com/questions/7877196/flask-sqlalchemy-create-several-tables-with-all-fields-identical