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

Sqlalchemy 的一个问题,在同一 transaction 中的 BinaryExpression 的比较问题

  •  
  •   MarcoQin · 2017-08-21 16:08:13 +08:00 · 1721 次点击
    这是一个创建于 2449 天前的主题,其中的信息可能已经有所发展或是发生改变。

    假设有一个 model 叫 StockModel, 有一个 Integer 型的 remaining 字段,然后有以下操作:

    stock = session.query(StockModel).first()
    with session.no_autoflush:
    	try:
        	stock = StockModel.remaining - 1  # sql: remaining = remaining - 1
            # 此时 stock 是 <sqlalchemy.sql.elements.BinaryExpression>
            # 若要再对 stock 进行比较,如下:
            if stock.remaining > 10:
            	pass
            # 则会直接报错:
            # TypeError: Boolean value of this clause is not defined
            # 我现在的解决方式是,如果 stock 是 BinaryExpression 的话,就避免
            # 进行比较,直接做减法操作,然后在 commit 之后做二次校验。。。
            # 如下:
            if isinstance(stock.remaining, BinaryExpression):
            	stock.remaining = StockModel.remaining - (stock.remaining.right.value + decrease_amount)
         	session.commit()
            # 在这里做二次校验:
            if stock.remaining < 0:
            	raise Expression("Stock not enough")
        except BaseException:
        	session.rollback()
        finally:
        	session.close()
    

    请问各位大佬,有没有更优雅的解决方案呢……在 sqlalchemy 的文档里徜徉了许久还是木有找到想要的解决办法……

    目前尚无回复
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2455 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 30ms · UTC 10:04 · PVG 18:04 · LAX 03:04 · JFK 06:04
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.