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

peewee update 的封装调用问题

  •  
  •   aoscici · 2020-07-02 00:33:12 +08:00 · 2008 次点击
    这是一个创建于 1366 天前的主题,其中的信息可能已经有所发展或是发生改变。

    假设我的数据模型:

    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 条回复    2020-07-03 11:07:07 +08:00
    111111111111
        1
    111111111111  
       2020-07-02 00:56:58 +08:00 via Android
    getattr?
    Trim21
        2
    Trim21  
       2020-07-02 01:00:05 +08:00 via Android
    {getattr(Book, key): value for key, value in updater.items()}
    aoscici
        3
    aoscici  
    OP
       2020-07-02 13:38:38 +08:00
    @Trim21 key 似乎只支持 Book.price 这样的类型, 直接用字符串会报错
    Trim21
        4
    Trim21  
       2020-07-02 15:20:53 +08:00 via Android
    @aoscici 这个 getattr 取出来的就是 Book.price
    chenqh
        5
    chenqh  
       2020-07-02 17:28:47 +08:00
    peewee 支持 dict 的类型的
    比如
    ```
    Book.update(price=29.9).where(author__eq="鲁迅")
    ```
    aoscici
        6
    aoscici  
    OP
       2020-07-02 18:10:24 +08:00
    @Trim21 谢谢, 确实是哈
    vegetableChick
        7
    vegetableChick  
       2020-07-03 11:07:07 +08:00
    condition_dict = {"author":"鲁迅", "id":1}

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

    q.execute()


    像是这样么 ~
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2827 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 29ms · UTC 13:15 · PVG 21:15 · LAX 06:15 · JFK 09:15
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.