django - 在 Tastypie 中将过滤器合并为一个查询

标签 django tastypie

这个问题在这里已经有了答案:




9年前关闭。




Possible Duplicate:
Django Tastypie Advanced Filtering: How to do complex lookups with Q objects



我有一个看起来像这样的美味模型资源:
class TaggedResource(ModelResource):
    tags = ListField()
    user = fields.ForeignKey(UserProfileResource, 'user')

    class Meta:
        queryset = Media.objects.all().order_by('-timestamp')
        authorization = MediaAuthorization()
        detail_allowed_methods = ['get', 'post', 'put', 'delete','patch']

    filtering = {
        #'user': ALL_WITH_RELATIONS,
        #exact is date, lt is less than lte less than equal to, etc
        'timestamp': ['exact', 'range', 'lt', 'lte', 'gte', 'gt'],
        'social_source': ALL,
        'media_type': ALL,
        'comment': ['exact', 'startswith', 'endswith', 'contains'],
        'media_text': ['exact', 'startswith', 'endswith', 'contains'],
    }

我需要在过滤器之间使用 OR 运算符,并且希望将查询合并为一个参数。例如,我想返回包含从评论字段或 media_text 字段过滤的单词“test”的对象。

这将是理想的:http://mysite.com/api/v1/tagged?q=test

其中 'q' 对两个字段执行 OR 过滤器。

这是可行的吗?

更新:这是我正在使用高级过滤器处理的内容,但我不确定如何获得 OR 语句:
def build_filters(self, filters=None):
    if filters is None:
        filters = {}

    orm_filters = super(TaggedResource, self).build_filters(filters)

    if 'q' in filters:
        orm_filters['comment__contains'] = filters['q']
        orm_filters['media_text__contains'] = filters['q'] 
    return orm_filters  

最佳答案

您通过覆盖 build_filters 做正确的事情,您可以使用 django 的 Q 类进行 AND/OR 查询,我在这里回答了类似的问题

Tastypie filtering with multiple values

这是另一个有趣的:

Tastypie Negation Filter

关于django - 在 Tastypie 中将过滤器合并为一个查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11696229/

相关文章:

django - Tastypie "always_return_data"选项更改响应状态代码

Django/Tastypie 图片上传 - 多部分 : None? 中的边界无效

python - tastypie 中的外键

Django-tastypie 创建 URL 层次结构

javascript - django 循环中的计数器

django - 设置可选用户名 django 用户

python - Django 查询集 If 语句永远不会计算为真?

python - 使用 tastypie 从 PointField 返回纬度和经度值

python - 在 Django 中添加动态电子邮件后端

python - Django Compressor 无法在生产环境中运行