烧瓶SQLAlchemy的。创建几个相同的所有领域的表 [英] Flask-SQLAlchemy. Create several tables with all fields identical

查看:254
本文介绍了烧瓶SQLAlchemy的。创建几个相同的所有领域的表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Flask和SQLAlchemy扩展。我需要定义几个模型类,它们将在MySQL数据库中创建表。这些表只会有不同的名称,它们中的所有字段名称/数据类型都是相同的。我如何定义所有这些表的类?我正在考虑一些继承,但我不太确定我到底该怎么做。

解决方案

只要在混合类

$ p $ from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()
$ b $ class MyMixin(object):
id = Column(Integer,primary_key = True)
data = Column(String)
$ b class MyModel1(MyMixin,Base):
__tablename__ ='models1'
$ b $ class MyModel2(MyMixin,Base) :
__tablename__ ='models2'


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.

解决方案

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'

这篇关于烧瓶SQLAlchemy的。创建几个相同的所有领域的表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆