Flask-SQLAlchemy. Create several tables with all fields identical

做~自己de王妃 提交于 2020-01-11 07:24:48

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!