问题描述
我想过滤多个包含多个查询的字段:
I want to filter multiple fields with multiple queries like this:
api/listings/?subburb=Subburb1, Subburb2&property_type=House,Apartment,Townhouse,Farm .. etc
有没有内置的方式,我看在django过滤器,但它似乎有限,我想我必须手动在我的api视图,但它变得凌乱,过滤器上过滤器过滤器
Are there any built in ways, I looked at django-filters but it seems limited, and I think I would have to do this manually in my api view, but its getting messy, filtering on filters on filters
推荐答案
过滤器上的过滤器过滤器不是乱码,它被称为链接过滤器
。
filtering on filters on filters is not messy it is called chained filters
.
连锁过滤器是必要的,因为有时候会有 property_type
有些时候没有:
And chain filters are necessary because sometime there is going to be property_type
some time not:
if property_type:
qs = qs.filter(property_type=property_type)
如果你以为会有多个查询,那么它仍然会在一个查询中执行,因为queryset是懒惰的。
If you are thinking there is going to be multiple queries then not, it will still executed in one query because queryset are lazy.
或者你可以建立一个dict并传递一次:
Alternatively you can build a dict and pass it just one time:
d = {'property_type:': property_type, 'subburb': subburb}
qs = MyModel.objects.filter(**d)
这篇关于Django REST框架 - 过滤的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!