如何重写这个在sqlalchemy orm上使用django orm的代码?
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发布于 2018-08-21 17:31:18
SQLAlchemy通过在映射的类上提供工具化属性来使用不同的方法,如“申报地图”中所解释的那样
在构造类时,声明式将所有
Column对象替换为称为描述符的特殊Python访问器;这是一个称为仪器仪表的进程。
然后,您可以使用这些属性来形成谓词表达式等,使用所谓的SQL表达式语言。
在形成实际表达式时,有一些相似之处,例如分别使用按位运算符|、&和~作为OR,以及不使用。或者,SQLAlchemy提供构造or_()、and_()和not_()。总之,您应该在ORM教程中阅读“查询”。
因此,如果您的模型类是例如Proxy,那么您的代码可能如下所示
# 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_filterhttps://stackoverflow.com/questions/51953600
复制相似问题