概述
def cached_query(key,model,my_filter=None,exclude=None,order_by=None,sliced=50): """ :param key: string used as key reference to store on Memcached :param model: model reference on which 'filter' will be called :param my_filter: dictionary containing the filter parameters (eg.: {'title': 'foo','category': 'bar'} :param sliced: integer limit of results from the query. The lower the better,since for some reason Django Memcached won't store thousands of entries in memory :param exclude: dictionary containing the exclude parameters (eg.: {'title': 'foo','category': 'bar'} :param order_by: tuple containing the list of fields upon which the model will be ordered. :return: list of models. Not a QuerySet,since it was sliced. """ result = cache.get(key,None) if not result: if my_filter: result = model.objects.filter(**my_filter) if exclude: result = result.exclude(**exclude) if order_by: result = result.order_by(*order_by) else: result = model.objects.all() result = result[:sliced] cache.set(key,result,cache_timeout) return result
如果我使用像”title’:’foo’,’name’:’bar’}这样的简单字典过滤查询集,它的工作方式非常好.然而,并非总是如此.我需要使用django.db.models.Q实用程序对需要OR条件的更复杂查询执行过滤器.
那么,我如何将这些参数作为字典传递给过滤器.这有什么办法吗?
from functools import reduce import operator from django.db.models import Q # your dict is my_filter q = model.objects.filter(reduce(operator.or_,(Q(**d) for d in [dict([i]) for i in my_filter.items()])))
减少or_连接OR上的Q表达式.
您还可以使用生成器表达式,其中包含dicts列表:
q = model.objects.filter(reduce(operator.or_,(Q(**d) for d in (dict([i]) for i in my_filter.items()))))
总结
以上是编程之家为你收集整理的python – 使用dict参数的带有OR条件的Django过滤器全部内容,希望文章能够帮你解决python – 使用dict参数的带有OR条件的Django过滤器所遇到的程序开发问题。
如果您也喜欢它,动动您的小指点个赞吧