推荐学习书目
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 · 5864 views
    This topic created in 4021 days ago, the information mentioned may be changed or developed.
    14 replies    2015-06-21 16:18:48 +08:00
    RIcter
        1
    RIcter  
       Jun 20, 2015
    Django 的 ORM 也要 save() 的_(:3」∠)_
    WildCat
        2
    WildCat  
    OP
       Jun 20, 2015
    @RIcter 额,可能是我表述不清楚。Django ORM:

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

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