sqlalchemy - 优雅的方式来处理几个可选的过滤器? [英] sqlalchemy - elegant way to deal with several optional filters?

查看:243
本文介绍了sqlalchemy - 优雅的方式来处理几个可选的过滤器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个包含serveral 可选过滤器的查询方法。我想要实现的是,如果我通过一些非None值过滤参数,然后做一个过滤器,如果过滤器的值为None,然后忽略它。

Suppose I have a query method with serveral optional filters. What I want to achieve is, If I pass some not None value to filter parameters then do a filter, if filter value is None, then just ignore it.

def get_query_results(filter1=None, filter2=None, ...):
    res = models.Item.query
    if filter1 is not None:
        res = res.filter(filter1=filter1)
    if filter2 is not None:
        res = res.filter(filter2=filter2)
    ....
    return res.all()

我想避免的是模式

if XXX:
    res.filter(XXX=XXX)

我想知道是否有更优雅的方式来实现这一点?

I wonder if there is any more elegant way to achieve this?

例如,传递各种过滤器作为参数?

For example, pass various filters as parameters?

或者,当过滤器值为None时,我们可以做一些魔法来省略过滤器。

Or maybe, we can do some magic to omit the filter when the filter value is None?

推荐答案

代码完全等同于你所展示的代码:

Code perfectly equivalent to the one you've shown is:

def get_query_results(*filters):
    res = models.Item.query
    for i, filt in enumerate(filters, 1):
        if filt is not None:
            d = {'filter{}'.format(i): filt}
            res = res.filter(**d)
    return res.all()

我不太确定为什么你需要 res.filter 的特定 filter1 的命名参数, filter2 等,但这个片段会做到没有你可以理解的避免重复的模式。

I'm not quite sure why you need the named argument to res.filter to be specifically filter1, filter2, etc, but this snippet will do it without the repetitious pattern that you understandably want to avoid.

的名称实际上是 filter1 filter2 等,只要必需的名称:

Should the names not actually be filter1, filter2, etc, that's OK as long as the required names are known:

NAMES = 'foo bar baz bat'.split()

def get_query_results(*filters):
    res = models.Item.query
    for name, filt in zip(NAMES, filters):
        if filt is not None:
            d = {name: filt}
            res = res.filter(**d)
    return res.all()


b $ b

这种变体在这种情况下可以工作。

This variant would work in this case.

这篇关于sqlalchemy - 优雅的方式来处理几个可选的过滤器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆