默认情况下是否存在否定过滤器。这个想法是,您可以在Django ORM中执行以下操作:
model.objects.filter(field!=value)
如果可能的话,我怎么能在饼中做到这一点。我试过了:
someapi.com/resource/pk/?field__not=value
someapi.com/resource/pk/?field__!=value
someapi.com/resource/pk/?field!=value
他们都给了我错误。
最佳答案
不幸的是没有。
问题在于,Tastypie的ModelResource类仅使用QuerySet的filter()方法,即它不使用应用于否定过滤器的exclude()。虽然没有filter()字段查找,但这意味着取反。有效查找为(在此SO post之后):
exact
iexact
contains
icontains
in
gt
gte
lt
lte
startswith
istartswith
endswith
iendswith
range
year
month
day
week_day
isnull
search
regex
iregex
但是,实现对“ __not_eq”之类的支持并不难。您需要做的就是修改apply_filters()方法,并用其余的“ __not_eq”分隔过滤器。然后,您应该将第一组传递给exclude(),将其余的传递给filter()。
就像是:
def apply_filters(self, request, applicable_filters):
"""
An ORM-specific implementation of ``apply_filters``.
The default simply applies the ``applicable_filters`` as ``**kwargs``,
but should make it possible to do more advanced things.
"""
positive_filters = {}
negative_filters = {}
for lookup in applicable_filters.keys():
if lookup.endswith( '__not_eq' ):
negative_filters[ lookup ] = applicable_filters[ lookup ]
else:
positive_filters[ lookup ] = applicable_filters[ lookup ]
return self.get_object_list(request).filter(**positive_filters).exclude(**negative_filters)
而不是默认值:
def apply_filters(self, request, applicable_filters):
"""
An ORM-specific implementation of ``apply_filters``.
The default simply applies the ``applicable_filters`` as ``**kwargs``,
but should make it possible to do more advanced things.
"""
return self.get_object_list(request).filter(**applicable_filters)
应该允许以下语法:
someapi.com/resource/pk/?field__not_eq=value
我还没有测试。它可能也可以用更优雅的方式编写,但是应该可以帮助您:)
关于django - 薄饼否定过滤器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9675127/