Python&Peewee - 动态 where 子句

标签 python mysql flask peewee

我目前正在与 Flask & Peewee 合作。恕我直言,这是一个很好的组合,但现在我已经到了 peewee 对于我的项目来说似乎“弱”的地步。可能是我,以错误的方式思考一些事情:)

下面的代码很好地描述了我的问题。

# dynamic data from somewhere outside my application 
# (does not really matter from where)
# how data really look like
dynamicInput = [(fieldname1 == 'abc'),(fieldname2 == 'def')]

# how data should look like (in a dynamic way)
dynamicInput = [(databasetable.fieldname1 == 'abc'), (databasetable.fieldname2 == 'def')]

# query database with peewee query
model = self.action_meta.model_clothing.select().where(dynamicInput).get()

由于缺少数据库表引用,where 子句无法使用 查询有用的结果。通过数据库表引用,我的意思是类似数据库表.fieldname。

所以问题是如何基于简单的字典/列表(键值对)动态创建有效的 where 子句。

最佳答案

只需使用DatabaseTable._meta.fields[field_name]或getattr(DatabaseTable, field_name)即可获取字段对象。您可以通过将字段对象与运算符和值组合来动态构造表达式。

关于Python&Peewee - 动态 where 子句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45776599/

相关文章:

mysql - order by 导致 select 查询返回空值

python - 如何减少 JSON 中的请求时间或将字典键替换为默认键?

python - 在 Flask-SqlAlchemy 中连接表

python - 无法将 `scipy.interpolate.RectBivariateSpline` 与 `matplotlib.pyplot,plot_surface` 一起使用

python - SQLAlchemy 使用关系()

mysql - 返回空结果集。不明白为什么

mysql - 表 'project_dev.users' 不存在

python - 如何在 Flask 中使用 url_for 中的变量?

PHP将包含空格的输入字符串传递给python文件

python - max 函数中的键的指导原则是什么?该键与 Python 中的字典键相关吗?例如 : max(arg1, arg2, *args[, key])