向Objects.filter添加额外的参数(通过Dict)? [英] Adding Extra Parameters to a Objects.filter (via Dict)?

查看:492
本文介绍了向Objects.filter添加额外的参数(通过Dict)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我们有一个 dvd 表,我们要搜索 price = 14.99 评级= 18 。我们可以做:

 #制作一些字典
dict1 = {}

#Adding一些东西
dict1 ['price'] = 14.99
dict1 ['rating'] 18

#使用dict作为过滤器
dvd.objects.filter(** dict1)

有没有办法添加额外的参数,如:

  dvd.objects.filter(title__icontains ='the')

我想为用户增加一些灵活性,因为目前他们可以选择他们想要搜索的字段,并指定他们想要什么。但是,我想搜索部分比赛,就像 __ icontains 一样。我也喜欢 __ gt __ lt



这是可能吗?

解决方案

我不知道你想做什么?要在最初的 dvd.objects.filter(** dict1)之后过滤其他字段?如果是这样,你可以简单地做:

  qs = dvd.objects.filter(** dict1)
qs。过滤器(title__icontains ='the')

记住,过滤器返回一个查询,所以你可以执行任何你想要的操作,就像你在 dvd.objects



如果你的意思是想在 dict 中添加 icontains ,那么你可以简单地分配 dict1 作为 price__icontains 而不是价格 p>

Say we have a dvd table where we want to search for price=14.99 and rating=18. We could do:

#Making some dictionary
dict1 = {}

#Adding some stuff
dict1['price']=14.99
dict1['rating']18

#Use dict as filter
dvd.objects.filter(**dict1)

Is there a way to add on extra parameters like:

dvd.objects.filter(title__icontains='the')

I'd just like to add a bit more flexibility for the user because at present they can choose what fields they'd like to search in and specify exactly what it is they want. However I'd like to search partial matches, like what __icontains does. I'd also like __gt, __lt.

Is this possible?

解决方案

I'm not sure what you want to do? Do you want to filter on additional fields after the initial dvd.objects.filter(**dict1)?? If so, you can simply do:

qs = dvd.objects.filter(**dict1)
qs.filter(title__icontains='the')

Remember, filter returns a queryset so you can perform any operations you want, just like you would on dvd.objects.

If, what you meant was you wanted to add icontains to something in dict, then you could simply assign the keys in dict1 as price__icontains instead of price.

这篇关于向Objects.filter添加额外的参数(通过Dict)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆