我设置了django-filter来过滤我的一些列表。这是其中之一,具有自定义格式:
class BookingListFiltersForm(forms.Form):
state__in = forms.MultipleChoiceField(
choices=Booking.STATE_CHOICES, required=False,
label=_("État"), widget=forms.CheckboxSelectMultiple)
source__in = forms.ModelMultipleChoiceField(
queryset=Platform.objects.all(), required=False,
label=_("Source"), widget=ModelSelect2Multiple(
url='autocomplete:platform'))
class BookingManagerFilter(filters.FilterSet):
payments__date = filters.DateFilter(method='payments__date_filter')
payments__method = filters.ChoiceFilter(
method='payments__method_filter',
choices=BookingPayment.METHOD_CHOICES,
)
class Meta:
model = Booking
fields = {
'period': [
'endswith', 'endswith__gte', 'endswith__lte',
'startswith', 'startswith__gte', 'startswith__lte',
],
'state': ['in'],
'source': ['in'],
'booking_date': ['date', 'date__lte', 'date__gte'],
'accommodation': ['in'],
'guest': ['exact']
}
def get_form_class(self):
return BookingListFiltersForm
def payments__date_filter(self, queryset, name, value):
return queryset.filter(**{name: value})
def payments__method_filter(self, queryset, name, value):
return queryset.filter(**{name: value})
表单是通过GET方法提交的。当字段“ source__in”为空时,查询字符串看起来像这样的“?state__in = 1”。在这种情况下,我的页面上没有任何结果(这是意外的,如果没有填写字段,我希望结果不会在该字段上进行过滤。)
我查看了调试工具栏,以获取有关已执行的SQL查询的更多信息。令人惊讶的是,我没有找到相关查询集的SQL查询! (例如,如果querystring为“?state__in = 1&source__in = 2”,则结果符合预期,我可以在调试工具栏中找到相关查询)
因此,我尝试使用print(str(filters.qs.query))
强制使用SQL查询。新的惊喜,这触发了EmptyResultSet
异常:
Traceback:
File "/home/tony/.venvs/cocoonr/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner
35. response = get_response(request)
File "/home/tony/.venvs/cocoonr/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response
128. response = self.process_exception_by_middleware(e, request)
File "/home/tony/.venvs/cocoonr/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response
126. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/tony/.venvs/cocoonr/lib/python3.6/site-packages/django/views/generic/base.py" in view
69. return self.dispatch(request, *args, **kwargs)
File "/home/tony/.venvs/cocoonr/lib/python3.6/site-packages/django/utils/decorators.py" in _wrapper
62. return bound_func(*args, **kwargs)
File "/home/tony/.venvs/cocoonr/lib/python3.6/site-packages/django/contrib/auth/decorators.py" in _wrapped_view
21. return view_func(request, *args, **kwargs)
File "/home/tony/.venvs/cocoonr/lib/python3.6/site-packages/django/utils/decorators.py" in bound_func
58. return func.__get__(self, type(self))(*args2, **kwargs2)
File "/home/tony/Workspace/cocoonr/utils/views/manager.py" in dispatch
29. return super().dispatch(*args, **kwargs)
File "/home/tony/.venvs/cocoonr/lib/python3.6/site-packages/django/views/generic/base.py" in dispatch
89. return handler(request, *args, **kwargs)
File "/home/tony/.venvs/cocoonr/lib/python3.6/site-packages/django/views/generic/list.py" in get
142. self.object_list = self.get_queryset()
File "/home/tony/Workspace/cocoonr/booking/views/manager.py" in get_queryset
73. queryset = super().get_queryset()
File "/home/tony/Workspace/cocoonr/utils/views/common.py" in get_queryset
118. print(self.filters.qs.query)
File "/home/tony/.venvs/cocoonr/lib/python3.6/site-packages/django/db/models/sql/query.py" in __str__
252. sql, params = self.sql_with_params()
File "/home/tony/.venvs/cocoonr/lib/python3.6/site-packages/django/db/models/sql/query.py" in sql_with_params
260. return self.get_compiler(DEFAULT_DB_ALIAS).as_sql()
File "/home/tony/.venvs/cocoonr/lib/python3.6/site-packages/django/db/models/sql/compiler.py" in as_sql
461. where, w_params = self.compile(self.where) if self.where is not None else ("", [])
File "/home/tony/.venvs/cocoonr/lib/python3.6/site-packages/django/db/models/sql/compiler.py" in compile
393. sql, params = node.as_sql(self, self.connection)
File "/home/tony/.venvs/cocoonr/lib/python3.6/site-packages/django/db/models/sql/where.py" in as_sql
98. raise EmptyResultSet
Exception Type: EmptyResultSet at /manager/booking/bookings/
Exception Value:
现在我被困住了,我不知道出了什么问题以及如何进一步调试。
为了进行测试,我尝试传递以下查询字符串:“?state__in = 1&source__in =”。在这种情况下,过滤工作正常,但是过滤器表单在字段“ source__in”中显示错误“«»不是有效值”。
此外,这是utils/views/common.py
中的相关混合:
class ListFilterMixin:
filters_class = None
default_filters = None
@cached_property
def filters(self):
return self.get_filters()
def get_filters(self):
if self.filters_class:
qstring = self.request.GET
if not qstring and self.default_filters:
qstring = QueryDict(self.default_filters)
return self.filters_class(
qstring, self.get_unfiltered_queryset(), request=self.request)
else:
return None
def get_queryset(self):
print(self.filters.qs.query) # <--- Line 118
# ...
def get_unfiltered_queryset(self):
return super().get_queryset()
还有booking/views/manager.py
中的视图类:
class BookingListView(ListView):
"""List of all bookings."""
model = Booking
default_filters = 'state__in=1'
filters_class = BookingManagerFilter
paginate_by = 30
ordering = '-pk'
def get_queryset(self):
queryset = super().get_queryset() # <--- Line 73
# ...
此外,您拥有完整的继承树,请注意,上面使用的ListView
是utils.views.manager.ListView
:
class ListView(BulkActionsMixin, ManagerMixin, BaseListView):
pass
BaseListView
是utils.views.common.ListView
:
class ListView(ListFilterMixin, AgencyMixin, ContextMixin, BaseListView):
pass
最后一个BaseListView
是django.views.generic.list.ListView
。
按照Kamil的建议,使用ipdb
进行调试,我注意到了一件奇怪的事情,很可能是此行为的原因:
ipdb> next
> /home.tony/.venvs/cocoonr/lib/python3.6/site-packages/django_filters/filters.py(167)filter()
166 def filter(self, qs, value):
--> 167 if value != self.null_value:
168 return super().filter(qs, value)
ipdb> self.null_value
'null'
ipdb> value
<QuerySet []>
ipdb> self.field_name
'source'
ipdb> self.lookup_expr
'in'
ipdb>
因此,后续代码认为source__in
不为空,并将source__in=empty_queryset
添加到过滤器中。我猜django然后猜猜结果无法评估为非空查询集,并保存了无用的查询。
是django-filters
中的错误,还是我做错了什么?
答案 0 :(得分:4)
我认为文档可以回答您的问题:
当前无法通过空字符串进行过滤,因为为空 值将被解释为跳过的过滤器。
GET http://localhost/api/my-model?myfield=
在文档中,您还将找到可能的解决方案的示例。我把其中一个放在这里
解决方案1:神奇的价值
您可以重写过滤器类的filter()方法以专门 检查魔术值。这类似于ChoiceFilter的null 价值处理。
GET http://localhost/api/my-model?myfield=EMPTY
class MyCharFilter(filters.CharFilter): empty_value = 'EMPTY' def filter(self, qs, value): if value != self.empty_value: return super(MyCharFilter, self).filter(qs, value) qs = self.get_method(qs)(**{'%s__%s' % (self.name, self.lookup_expr): ""}) return qs.distinct() if self.distinct else qs
现在,我觉得没有足够的信息来解决您的问题。我在你的问题下发表了评论。如果您可以提供这些额外的信息,将极大地帮助您了解发生了什么。
以下是一些提示,可以帮助您跟踪此错误:
在行前放置断点import ipdb;ipdb.set_trace()
File "/home/tony/.venvs/cocoonr/lib/python3.6/site-packages/django/views/generic/list.py" in get
142. self.object_list = self.get_queryset()
我怀疑您应该在https://github.com/carltongibson/django-filter/blob/82a47fb7bbddedf179f110723003f3b28682d7fe/django_filters/filterset.py#L215中找到罪魁祸首
您可以这样做
class BookingManagerFilter(filters.FilterSet):
# your previous code here
def filter_queryset(self, queryset):
import ipdb;ipdb.set_trace()
return super(BookingManagerFilter, self)filter_queryset(queryset):
运行您的端点,ipdb将停止该应用程序,您将能够进入代码并对其进行检查。
答案 1 :(得分:1)
我终于弄清楚了这个问题。
显然,django-filters
无法正确处理外键的查询in
。例如,source__in
的默认过滤器是ModelChoiceFilter
。所以我必须明确地将其定义为ModelMultipleChoiceFilter
。
但是,我遇到的另一个问题是source__in=10&source__in=7
大致转换为Q(source__in=10) | Q(source__in=7)
。这是一个例外,因为10和7是不可迭代的。因此,我将代码更改为使用exact
查找而不是in
,但是仍然使用ModelMultipleChoiceFilter
。最后,给出以下内容:
class BookingListFiltersForm(forms.Form):
state__in = forms.MultipleChoiceField(
choices=Booking.STATE_CHOICES, required=False,
label=_("État"), widget=forms.CheckboxSelectMultiple)
source = forms.ModelMultipleChoiceField(
queryset=Platform.objects.all(), required=False,
label=_("Source"), widget=ModelSelect2Multiple(
url='autocomplete:platform'))
class BookingManagerFilter(filters.FilterSet):
source = filters.ModelMultipleChoiceFilter(
queryset=Platform.objects.all())
payments__date = filters.DateFilter(method='payments__date_filter')
payments__method = filters.ChoiceFilter(
method='payments__method_filter',
choices=BookingPayment.METHOD_CHOICES,
)
class Meta:
model = Booking
fields = {
'period': [
'endswith', 'endswith__gte', 'endswith__lte',
'startswith', 'startswith__gte', 'startswith__lte',
],
'state': ['in'],
'source': ['exact'],
'booking_date': ['date', 'date__lte', 'date__gte'],
'accommodation': ['exact'],
'guest': ['exact']
}
def get_form_class(self):
return BookingListFiltersForm