V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
推荐学习书目
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
aoscici
V2EX  ›  Python

peewee update 的封装调用问题

  •  
  •   aoscici · Jul 2, 2020 · 2763 views
    This topic created in 2133 days ago, the information mentioned may be changed or developed.

    假设我的数据模型:

    class Book(Model):
        id = PrimaryKeyField()
        title = CharField(max_length=64, unique=True)
        author = CharField(max_length=64)
        publisher = CharField(max_length=64)
        price = DecimalField(max_digits=10, decimal_places=2)
        desc = CharField(max_length=256)
    

    如果我要根据条件更新的话, 找了很多文档基本都是:

    Book.update({Book.price: 29.9}).where(Book.author == '鲁迅')

    但外部调用的话只能提供字段名比如 {'price': 29.9}, {'author': '鲁迅'}, 怎样才能拼出上边的语句?

    7 replies    2020-07-03 11:07:07 +08:00
    111111111111
        1
    111111111111  
       Jul 2, 2020 via Android
    getattr?
    Trim21
        2
    Trim21  
       Jul 2, 2020 via Android
    {getattr(Book, key): value for key, value in updater.items()}
    aoscici
        3
    aoscici  
    OP
       Jul 2, 2020
    @Trim21 key 似乎只支持 Book.price 这样的类型, 直接用字符串会报错
    Trim21
        4
    Trim21  
       Jul 2, 2020 via Android
    @aoscici 这个 getattr 取出来的就是 Book.price
    simple2025
        5
    simple2025  
       Jul 2, 2020
    peewee 支持 dict 的类型的
    比如
    ```
    Book.update(price=29.9).where(author__eq="鲁迅")
    ```
    aoscici
        6
    aoscici  
    OP
       Jul 2, 2020
    @Trim21 谢谢, 确实是哈
    vegetableChick
        7
    vegetableChick  
       Jul 3, 2020
    condition_dict = {"author":"鲁迅", "id":1}

    q = Book.update({"price":30}).where(
    *[
    getattr(Book, key) == value for key, value in condition_dict.items()
    ]
    )

    q.execute()


    像是这样么 ~
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   2767 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 43ms · UTC 08:26 · PVG 16:26 · LAX 01:26 · JFK 04:26
    ♥ Do have faith in what you're doing.