V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
pppguest3962
V2EX  ›  Python

SQLAlchemy ORM,如何实现模板化建表?

  •  
  •   pppguest3962 · 2020-08-01 21:21:15 +08:00 · 1907 次点击
    这是一个创建于 1355 天前的主题,其中的信息可能已经有所发展或是发生改变。
    Base = declarative_base()
    engine = create_engine("mysql+pymysql://root:[email protected]:3306/testcreattbl?charset=utf8",echo=False)
    Session = sessionmaker(bind=engine)
    session = Session()
    metadata = MetaData(engine)
    
    class tbl_Items(Base):
        __tablename__ = 'Item2017'
    
        id = Column(INTEGER(64), primary_key=True)
        类型 = Column(String(8))
        序号 = Column(SMALLINT())
        变化时间 = Column(DateTime)
        重量 = Column(DECIMAL(6, 3))
        长 = Column(DECIMAL(6, 3))
        宽 = Column(DECIMAL(6, 3))
        高 = Column(DECIMAL(6, 3))
        UpdateTime = Column(DateTime)
        SQLTAG = Column(String(20))
        __table_args__ = ({'comment': '[ItemsXXX]'})
    
    class tbl_apple(Base):
       #省略
    
    class tbl_banana(Base):
       #省略
    
    ret = engine.dialect.has_table(engine, 'Item2020')
    if not ret:
         tbl_Items.__tablename__ = ''Item2020"
         # 这里如何创建一张"Item2020"的表?(同结构 class tbl_Items)
    

    假如我用了 base.metadata.create_all(engine)
    testcreattbl 将会其它无关的 tbl_apple,tbl_banana 表都创建了。。。

    5 条回复    2020-08-04 09:08:29 +08:00
    iConnect
        1
    iConnect  
       2020-08-01 22:26:07 +08:00 via Android
    base 本来就是公用的抽出来,你不复用的如果加判断(不知道 sqlalchemy 是不是支持)来处理,还不如在子类里单独写的
    pppguest3962
        2
    pppguest3962  
    OP
       2020-08-02 13:42:00 +08:00
    @iConnect ”子类里单独写?“,没能理解这个意思。。。。。,继承了一个子类,如何用这个子类建表呢?
    siteshen
        3
    siteshen  
       2020-08-02 15:58:15 +08:00
    你调用 `create_all` 函数,当然会 `create all`了。你不指定,`create_all` 怎么知道你想排除哪些表呢。
    yzk66880
        4
    yzk66880  
       2020-08-02 22:36:04 +08:00
    啥叫模板化建表? 嫌 create_all 的方式不灵活的话 就 alembic 做表管理
    pppguest3962
        5
    pppguest3962  
    OP
       2020-08-04 09:08:29 +08:00
    谢谢各位,
    ORM 这种映射方式应该是不能直接这么做,
    我用了另外一个方式,用 CrateTable(),获取旧表的原生 sql create 语句成 string 字符串,字符串修改新表名,再 conn.execute(新字符串)。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   5257 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 30ms · UTC 07:36 · PVG 15:36 · LAX 00:36 · JFK 03:36
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.