如何使用允许通过一个模型字段的多个值进行查询的 django-filter 构建过滤器 class
How to build filter class using django-filter that allows to query by multiple values of one model field
我必须构建必须允许按多个值过滤的端点。它必须看起来像这样:
http://example.com/page?field=1&field=2&filed=3
假设 field
是 MyModel
的 IntegField
。我想通过此 field
.
中的任何值进行查询
我想执行这样或类似的查询+验证查询参数列表
MyModel.objects.filter(field__in=[1,2,3])
django-filter(https://django-filter.readthedocs.io/en/stable/) 库看起来很有前途,但在文档中我还没有找到一种简单的方法来完成如此简单的事情。我怎样才能做到这一点?
验证也很重要。我不想允许使用这样的参数执行查询 field=yolo
到目前为止,我得到的代码不支持验证
import django_filters as df
from django.forms.widgets import SelectMultiple
class MyFilter(df.FilterSet):
id = df.Filter(required=False, field_name="id", widget=SelectMultiple(), lookup_expr="in")
class Meta:
model = MyModel
fields = ["id"]
也许不是最优雅的方式,但这就是我实现目标的方式:
from django_filters.fields import BaseCSVField
from django_filters.widgets import QueryArrayWidget
class MyBaseCSVField(BaseCSVField):
base_widget_class = QueryArrayWidget
class MyBaseInFilter(df.BaseInFilter):
base_field_class = MyBaseCSVField
class NumberInFilter(MyBaseInFilter, df.NumberFilter):
pass
class MytFilter(df.FilterSet):
field = NumberInFilter()
class Meta:
modem = MyModel
fields = ("field", )
所以这里的关键是 QueryArrayWidget
并且来自 docstrin:
1. Values can be provided as csv string: ?foo=bar,baz
2. Values can be provided as query array: ?foo[]=bar&foo[]=baz
3. Values can be provided as query array: ?foo=bar&foo=baz
在我看来,这个库通常没有很好的文档记录。
我必须构建必须允许按多个值过滤的端点。它必须看起来像这样:
http://example.com/page?field=1&field=2&filed=3
假设 field
是 MyModel
的 IntegField
。我想通过此 field
.
我想执行这样或类似的查询+验证查询参数列表
MyModel.objects.filter(field__in=[1,2,3])
django-filter(https://django-filter.readthedocs.io/en/stable/) 库看起来很有前途,但在文档中我还没有找到一种简单的方法来完成如此简单的事情。我怎样才能做到这一点?
验证也很重要。我不想允许使用这样的参数执行查询 field=yolo
到目前为止,我得到的代码不支持验证
import django_filters as df
from django.forms.widgets import SelectMultiple
class MyFilter(df.FilterSet):
id = df.Filter(required=False, field_name="id", widget=SelectMultiple(), lookup_expr="in")
class Meta:
model = MyModel
fields = ["id"]
也许不是最优雅的方式,但这就是我实现目标的方式:
from django_filters.fields import BaseCSVField
from django_filters.widgets import QueryArrayWidget
class MyBaseCSVField(BaseCSVField):
base_widget_class = QueryArrayWidget
class MyBaseInFilter(df.BaseInFilter):
base_field_class = MyBaseCSVField
class NumberInFilter(MyBaseInFilter, df.NumberFilter):
pass
class MytFilter(df.FilterSet):
field = NumberInFilter()
class Meta:
modem = MyModel
fields = ("field", )
所以这里的关键是 QueryArrayWidget
并且来自 docstrin:
1. Values can be provided as csv string: ?foo=bar,baz
2. Values can be provided as query array: ?foo[]=bar&foo[]=baz
3. Values can be provided as query array: ?foo=bar&foo=baz
在我看来,这个库通常没有很好的文档记录。