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
Kcelone
V2EX  ›  Python

Python + sqlalchemy 操作 mysql 的 JSON 类型

  •  
  •   Kcelone · 2019-01-09 20:09:02 +08:00 · 4497 次点击
    这是一个创建于 1905 天前的主题,其中的信息可能已经有所发展或是发生改变。

    针对于 MySQL 的 JSON 类型,官方上已经做了详细的介绍,在此,简单啰嗦几句吧,毕竟曾经没怎么遇到过。

    1. sql 脚本形式: 创建:create table stu(id int primary key, name varchar(20), remark JSON); 插入:insert into stu(id, name, remark) values(1, 'ha', '{'sc':'1a', 'mc':'2b'}'); 更新:update stu set remark = json_set(remark, '$.sc', '3a'); 删除:update stu set remark = json_remove(remark, '$.sc'); 增键:update stu set remark = json_set(remark, '$.tc', '5e');

      对于这些操作,是使用 sql 脚本进行,需要执行原生 sql 脚本。但平常更多使用的是 ORM 形式。

    2. orm 形式: 对于 ORM 形式,当然也可以使用 嵌入式的 sql 脚本进行完成,(此处不再说)。 或着结构对象来做。 比如上面的这个表,对于 ORM 形式,应该有一个 model 与之对应: 可以为: class Stu: id = Column(types.integer, primary_key=True) name = Column(types.String(20)) remark = Column(types.JSON)

      这个时候,可以这么做: the_stu = self.db_session.query(Stu).filter(Stu.id == uid).first() rem = the_stu.remark # 备份 the_stu.remark=None
      db_session.flush() # 具体为什么这么做还没明白,直接赋值不起作用。 rem['news'] = 'newsss' # 添加新值 the_stu.remark = rem # 将新的对象重新赋给模型对象的属性。 db_session.commit()

    不知道还有没有更好的解决方式,希望多多指教,大家都可以少走弯路,提高工作效率,一起学习加群 902788038, 群里也有 HR 小姐姐们,在进步的同时也祝愿能找到心仪工作。

    2 条回复    2019-01-10 15:57:33 +08:00
    fanhaipeng0403
        1
    fanhaipeng0403  
       2019-01-09 23:32:49 +08:00
    Kcelone
        2
    Kcelone  
    OP
       2019-01-10 15:57:33 +08:00
    @fanhaipeng0403 不忙了学习下,谢谢。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1055 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 22ms · UTC 22:39 · PVG 06:39 · LAX 15:39 · JFK 18:39
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.