peewee update 的封装调用问题

2020-07-02 00:33:12 +08:00
 aoscici

假设我的数据模型:

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': '鲁迅'}, 怎样才能拼出上边的语句?

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


像是这样么 ~

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/686402

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX