dict过滤 python_python – 使用dict参数的带有OR条件的Django过滤器

我在我的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条件的更复杂查询执行过滤器.

那么,我如何将这些参数作为字典传递给过滤器.这有什么办法吗?

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值