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

请教关于 django 的 orm 语句同时修改多条数据以及 flush 操作

  •  
  •   kayseen · 2020-04-16 09:35:11 +08:00 · 2399 次点击
    这是一个创建于 1443 天前的主题,其中的信息可能已经有所发展或是发生改变。

    tips: django 使用的 mysql, 以往用的是 flask 的 sqlalchemy, 比如同时修改了两个不同表的两条数据 user1 的 name=1,class2 的 name=class2,(两条数据没有关联关系), 我可以 model.add(user1),model.add(class2),最后 model.commit()一次性提交,

    但是在 django 的 orm 中, 如果有上述的场景, 一次性提交两条修改的数据(开事物?),该怎么实现呢?

    找到了 django 的批量创建 bulk_update(), 但是此方法只支持批量更新同张表的多条数据,并且需要指定 fields

    问题: 1.批量修改多张表的多条数据怎么一次性提交保存? 2.django 有没有在提交数据之前的 flush 操作(在创建新数据的时候,flush 操作可以获取新数据的 id,但是此时数据并没有保存到 mysql 中)

    5 条回复    2020-04-16 10:05:29 +08:00
    chen774553620
        1
    chen774553620  
       2020-04-16 09:42:32 +08:00
    from django.db import transaction
    with transaction.atomic:
    kayseen
        2
    kayseen  
    OP
       2020-04-16 09:47:44 +08:00
    @chen774553620
    了解, 真棒~
    Vegetable
        3
    Vegetable  
       2020-04-16 09:47:56 +08:00   ❤️ 1
    kayseen
        4
    kayseen  
    OP
       2020-04-16 10:03:42 +08:00
    @Vegetable
    这个东西看过啦哈哈, 请问您知道关于 django 的 flush 操作吗?
    EricCartmann
        5
    EricCartmann  
       2020-04-16 10:05:29 +08:00 via iPhone
    一楼已经终结这个问题。transaction 模块完美解决,加上 with transaction.atomic()还可以提供事务的特性👍🏿,引入一个 savepoint 还可以回滚。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   5396 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 28ms · UTC 07:35 · PVG 15:35 · LAX 00:35 · JFK 03:35
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.