django - 薄饼否定过滤器

标签 django api tastypie

默认情况下是否存在否定过滤器。这个想法是,您可以在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/

相关文章:

python - 错误通用详细 View 必须使用对象 pk 或 slug 调用,即使使用 pk

api - 错误 414 - 请求的 URL 太大而无法处理

c++ - 如何覆盖 Py_GetPrefix()、Py_GetPath()?

python - 在 django/tastypie 资源中传递请求变量

python - 在 Django 中,request.META[] 是为请求添加特定信息的正确位置吗?

django - Celery+Docker+Django -- 让任务工作

python - 如何通过一个请求创建多个资源Django Rest Framework?

ruby-on-rails - token 认证注销 : should I delete the token?

python - AttributeError at/api/project/'Query' 对象没有属性 'query_terms' tastypie

python - Django 管理设置