python – 使用dict参数的带有OR条件的Django过滤器
发布时间:2021-01-17 06:43:23 所属栏目:Python 来源:互联网
导读:我在我的Django应用程序上有一个函数,我执行一些Queryset操作并将其结果设置为Memcache.由于它是一种功能,因此必须具有一般用途.因此,为了使其可重用,我将dict作为过滤和排除操作的参数传递.这是功能: def cached_query(key, model, my_filter=None, exclude
|
我在我的Django应用程序上有一个函数,我执行一些Queryset操作并将其结果设置为Memcache.由于它是一种功能,因此必须具有一般用途.因此,为了使其可重用,我将dict作为过滤和排除操作的参数传递.这是功能: 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条件的更复杂查询执行过滤器. 那么,我如何将这些参数作为字典传递给过滤器.这有什么办法吗? 解决方法您可以将字典重组为单个键值字典列表,并在Q表达式中的每个字典中使用解包,如下所示: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())))) (编辑:吉安站长网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容
- 如何在django python中用json替换simplejson?
- python源代码中的sys模块在哪里?
- python – 基本的openGL,顶点缓冲区和pyglet
- python – Scipy:加快2D复数积分的计算
- 在Python的Cmd.cmd中完成filename tab-completion
- 范围 – Python的非本地取决于层次结构的级别?
- python – 确认import *和xxx导入之间的区别*
- python – 是subprocess.Popen不线程安全吗?
- 对相关python进口的极限答案
- django-forms – 如何使用modelformset_factory创建一个空的
