推荐学习书目
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 · Aug 21, 2017 · 2162 views
    This topic created in 3212 days ago, the information mentioned may be changed or developed.

    假设有一个 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 的文档里徜徉了许久还是木有找到想要的解决办法……

    No Comments Yet
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   894 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 30ms · UTC 22:19 · PVG 06:19 · LAX 15:19 · JFK 18:19
    ♥ Do have faith in what you're doing.