首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >sqlalchemy有像django中的Q这样的过滤器对象吗?

sqlalchemy有像django中的Q这样的过滤器对象吗?
EN

Stack Overflow用户
提问于 2018-08-21 17:06:42
回答 1查看 1.1K关注 0票数 3

如何重写这个在sqlalchemy orm上使用django orm的代码?

代码语言:javascript
复制
list_of_filters = [Q(active=True)]

if self.proxy_anonymity:
    list_of_filters.append(Q(anonymity=True))

if self.proxy_https:
    list_of_filters.append(Q(https=True))

if hasattr(spider, 'bad_proxies') and spider.bad_proxies:
    list_of_filters.append(~Q(ip__in=spider.bad_proxies))

proxy_filter = reduce(operator.and_, list_of_filters)

return proxy_filter
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-08-21 17:31:18

SQLAlchemy通过在映射的类上提供工具化属性来使用不同的方法,如“申报地图”中所解释的那样

在构造类时,声明式将所有Column对象替换为称为描述符的特殊Python访问器;这是一个称为仪器仪表的进程。

然后,您可以使用这些属性来形成谓词表达式等,使用所谓的SQL表达式语言

在形成实际表达式时,有一些相似之处,例如分别使用按位运算符|&~作为OR,以及不使用。或者,SQLAlchemy提供构造or_()and_()not_()。总之,您应该在ORM教程中阅读“查询”

因此,如果您的模型类是例如Proxy,那么您的代码可能如下所示

代码语言:javascript
复制
# Note that it is redundant to compare a boolean column with a boolean value.
# Just use the value of the column itself.
list_of_filters = [Proxy.active]

if self.proxy_anonymity:
    # Again, use a boolean column as is.
    list_of_filters.append(Proxy.anonymity)

if self.proxy_https:
    list_of_filters.append(Proxy.https)

if hasattr(spider, 'bad_proxies') and spider.bad_proxies:
    list_of_filters.append(Proxy.ip.in_(spider.bad_proxies))

proxy_filter = and_(*list_of_filters)

return proxy_filter
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51953600

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档