python - 如何根据条件动态构建查询?

标签 python google-app-engine app-engine-ndb

我想根据用户请求,根据可能条件的范围 (0-4) 查询数据存储。 NDB 中的查询构建如下:

query = Account.query(Account.userid >= 40, Account.userid < 50)

有什么办法可以做类似的事情:

myfilter = []
myfilter.push('Account.userid >= 40')
myfilter.push('Account.userid < 50')
myfilter.push('Account.name == "John"')
query = Account.query(*myfilter)

可能有 0 到 4 个过滤器参数,具体取决于条件。我的假设(这可能是错误的)是如果不需要的话,省略过滤器比拥有一个包罗万象的过滤器(例如 Account.userid == *)更理想。

我知道您可以链接过滤器,但由于查询对象是不可变的,所以不确定这是否对我有帮助。

最佳答案

有一种更优雅的方法可以做到这一点。顺便说一句,它更加动态:

def build_query_by(ndb_class, filters, sorts):
    """
    ndb_class: the ndb model class to query
    filters: a list of tuples of properties, operations and values
    sorts: a list of tuples of properties and order symbol
    """
    q = ndb_class.query()
    for prop, operation, value in filters:
        if operation == '==':
            q = q.filter(getattr(ndb_class, prop) == value)
        elif operation == '>=':
            q = q.filter(getattr(ndb_class, prop) >= value)
        elif operation == '<=':
            q = q.filter(getattr(ndb_class, prop) <= value)
        # more operations...

    for prop, symbol in sorts:
        if symbol == '-':
            q = q.order(-getattr(ndb_class, prop))
        else:
            q = q.order(getattr(ndb_class, prop))
    return q

关于python - 如何根据条件动态构建查询?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41554694/

相关文章:

google-app-engine - App Engine ndb 中的结构化数据并加快查询速度

python - 使用 numpy 计算精度和准确度

python - 帮助构建一对多关系的 GQL 查询

python - 将远程 FIFO 队列实现为 Python GAE 应用程序的最简单方法是什么?

python - 将Django部署到Google云平台

python - 将结构化属性添加到 NDB 中的模型

python - 当我在图像上打印文本并且它超出了图像的框架时,如何在 OpenCV 中包装文本?

python - 我们应该为 python 变量名使用哪些缩写?

python - tf 转换器已全部映射,但仍遇到 Unresolved 自定义操作

PYTHON-数据存储中 TextProperty 的属性 "{field_name}"的值超过 1048487 个字节