Tastypie否定过滤器 [英] Tastypie Negation Filter

查看:105
本文介绍了Tastypie否定过滤器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有默认提供一个否定过滤器。我们的想法是,你可以做在Django的ORM以下内容:

Is there a negation filter available by default. The idea is that you can do the following in the django ORM:

model.objects.filter(field!=value)

我怎样才能做到这一点在tastypie如果这甚至有可能。我想:

How can I do that in tastypie if that is even possible. I tried:

someapi.com/resource/pk/?field__not=value
someapi.com/resource/pk/?field__!=value
someapi.com/resource/pk/?field!=value

和所有的人给我的错误。

And all of them given me errors.

推荐答案

不幸的是有没有。

问题在于Tastypie的ModelResource类只使用查询集的过滤器()的方法,即它不使用排除(),其应该被用于负滤波器。没有过滤器()字段查找这将意味着否定虽然。有效的查找(在此之后的SO帖子):

The problem is that Tastypie's ModelResource class uses the filter() method of the QuerySet only, i.e. it does not use exclude() which should be used for negative filters. There is no filter() field lookup that would mean negation though. The valid lookups are (after this 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。然后,你应该通过第一组排除(),其余过滤()。

However it shouldn't be so hard to implement the support for something like "__not_eq". All you need to do is to modify the apply_filters() method and separate filters with "__not_eq" from the rest. Then you should pass the first group to exclude() and the rest to 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)

应该允许的语法如下:

should allow for the following syntax:

someapi.com/resource/pk/?field__not_eq=value

我没有测试它。这也许可以写在太更优雅的方式,但应该让你去:)

I haven't tested it. It could probably be written in more elegant way too, but should get you going :)

这篇关于Tastypie否定过滤器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆