django – Tastypie Negation过滤器

默认情况下是否有可用的否定过滤器。这个想法是,您可以在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()。没有过滤器()字段查找,这意味着否定。有效的查找是(在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(),其余的将过滤器()。

就像是:

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

我还没有测试它可能可以写得更优雅的方式,但应该让你去:)

翻译自:https://stackoverflow.com/questions/9675127/tastypie-negation-filter

转载注明原文:django – Tastypie Negation过滤器