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

初用 SQLAlchemy ,觉得很不习惯的是,每次 add(), delete() 之后,还需要 commit() ,与 ActiveRecord\Django ORM 这点很不一样,这样设计有什么好处吗?

  •  
  •   WildCat · Jun 20, 2015 · 6085 views
    This topic created in 4159 days ago, the information mentioned may be changed or developed.
    14 replies  •  2015-06-21 16:18:48 +08:00
    RIcter
    RIcter
    Jun 20, 2015
    1
    Django 的 ORM 也要 save() 的_(:3」∠)_
    WildCat
    WildCat
    OP
    Jun 20, 2015
    2
    @RIcter 额,可能是我表述不清楚。Django ORM:

    >>> fruit = Fruit.objects.create(name='Apple')
    >>> fruit.name = 'Pear'
    >>> fruit.save()

    就是一个对象直接 save() 就可以了,之后没有 commit()。
    但是 SQLAlchemy add() 之后还需要 commit() 。
    kxxoling
    kxxoling
    Jun 20, 2015❤️1
    3
    @WildCat 可以设置 autocommit 啊,不过那样就不够灵活了。
    ChanneW
    ChanneW
    Jun 20, 2015❤️1
    4
    ponyorm 连 save 都不需要
    hibernate 需要 factory.getsession session.startsession new session.save session.commit session.close factory.close
    WildCat
    WildCat
    OP
    Jun 20, 2015
    5
    @kxxoling 好吧,谢啦。
    主要目前用得都比较低端,还没想到这么设计的优势
    kxxoling
    kxxoling
    Jun 20, 2015
    6
    @WildCat 有时候有几条命令必须是整体的,要么都成功,要么都失败,比如银行转账会减你的账户余额增加别人的,如果中间出现问题了就需要整体回滚。如果分开了就会出现你账户少钱了,对方也没多的纠纷情况。从数据库基础开始看吧~
    WildCat
    WildCat
    OP
    Jun 20, 2015
    7
    @kxxoling 好吧,那是事务啊,但是平时没必要都这么做吧。
    clino
    clino
    Jun 20, 2015 via Android
    8
    看起来commit和save作用差不多,没多麻烦啊
    lilydjwg
    lilydjwg
    Jun 20, 2015❤️1
    9
    @WildCat 对就是事务。我平时用数据库经常会需要的东西。我最不喜欢 MongoDB 的地方。
    当然你不需要事务的话可以设置 autocommit 模式。
    kxxoling
    kxxoling
    Jun 20, 2015 via iPad❤️1
    10
    @WildCat 不考虑事务的话也可以减少数据库请求的次数,稍微降低数据库压力。(如果是远程数据库就更是如此了。
    neoblackcap
    neoblackcap
    Jun 20, 2015❤️3
    12
    具体SQLAlchemy是Data Mapper,我觉得它跟Active Record类的ORM最大的不同就是,数据库模型可以跟代码中的数据结构解耦。这个解耦了就不得了,它会衍生出很多强大的使用方法,比如泛型查找之类的。而且对于大型项目更好维护。
    onlyice
    onlyice
    Jun 21, 2015 via Android
    13
    @neoblackcap 有没有更深入的讲解或者资料来说明这点呢?
    neoblackcap
    neoblackcap
    Jun 21, 2015❤️1
    14
    @onlyice 具体的话可以去看看Martin Fowler的博客,他是这方面的专家。两个典型分别就是Java的hibernate对应data mapper,Active Record对应RoR
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   1645 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 33ms · UTC 13:19 · PVG 21:19 · LAX 05:19 · JFK 08:19
    ♥ Do have faith in what you're doing.