推荐学习书目
› 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
renvip
V2EX  ›  Python

sqlalchemy 动态获取 model 类

  •  
  •   renvip · Mar 30, 2021 · 2862 views
    This topic created in 2005 days ago, the information mentioned may be changed or developed.
    RT,程序会新增表,但这些表的数据结构一致,如何写一个方法,动态获取 model 类,然后使用 orm 进行表的增删改查。网上有一些,但是可能有坑和缺陷,问问大佬有没有实现过,避免造轮子。思路,定义一个 get_model(tablename)方法,传递表名,返回一个 model 类,然后可以用 model 类直接进行表的增删改查,至于创建新表,在方法里判断一下,这个表在数据库存在不存在,存在就不创建,不存在就创建。
    参考链接:base64
    aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L2phY2tlMTIxL2FydGljbGUvZGV0YWlscy84OTI5MjcyNg==
    aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L0pfT2JqZWN0L2FydGljbGUvZGV0YWlscy84MDExMTc0Ng==
    aHR0cHM6Ly93d3cuaXQ2MTAuY29tL2FydGljbGUvMTI5MjYwMzk0NjAxOTM5NzYzMi5odG0=
    3 replies  •  2021-04-01 09:49:26 +08:00
    wonderay
        2
    wonderay  
       Mar 31, 2021
    "至于创建新表,在方法里判断一下,这个表在数据库存在不存在,存在就不创建,不存在就创建。"

    你是想通过表结构, 生成对应的 model, 既然表都不存在,model 也就无从生成, 那还怎么创建呢?
    renvip
        3
    renvip  
    OP
       Apr 1, 2021
    @wonderay 我可以使用 db.create_all()建表
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   2522 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 23ms · UTC 09:19 · PVG 17:19 · LAX 02:19 · JFK 05:19
    ♥ Do have faith in what you're doing.