【问题标题】:Advance filtering with list of elements using django tastypie使用 django sweetpie 使用元素列表进行高级过滤
【发布时间】:2016-09-01 23:03:59
【问题描述】:

我正在使用MultiSelectField 在我的 django 管理员中选择多个选项,它为我选择的所有选项的后端字段创建一个数组。然后我使用django tastypie's List Field 来确保它是 api 返回的元素列表。

我的问题是,当我在浏览器中输入/api/?brand_category=Clothing&q=athletic,bohemian 时,我正在构建过滤器,它只返回一个空列表。所以我想知道我是否做错了什么?或者没有正确构建我的过滤器?

models.py

class Brand(models.Model):

    # category
    brand_category = MultiSelectField(max_length=100, blank=True, choices=categories))

    # style
    brand_style = MultiSelectField(max_length=100, choices=styles, blank=True)

api.py

class LabelResource(ModelResource):

    brand_category = fields.ListField(attribute='brand_category')

    brand_style = fields.ListField(attribute='brand_style')

    class Meta:

        filtering = {
            "brand_category": ALL,
            "brand_style": ALL,
            "q": ['exact', 'startswith', 'endswith', 'contains', 'in'],

        }


def build_filters(self, filters=None):
    if filters is None:
        filters = {}

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


    if('q' in filters):
        query = filters['q']

        qset = (
            Q(brand_style__in=query) 
        )

        orm_filters.update({'custom': qset})

    return orm_filters

def apply_filters(self, request, applicable_filters):
    if 'custom' in applicable_filters:
        custom = applicable_filters.pop('custom')

    else:
        custom = None

    semi_filtered = super(LabelResource, self).apply_filters(request, applicable_filters)

    return semi_filtered.filter(custom) if custom else semi_filtered

JSON 响应

{
  "brand_category": [
    "Clothing"
  ],
  "brand_style": [
    "athletic",
    "bohemian",
    "casual"
  ]
}

【问题讨论】:

    标签: python django tastypie


    【解决方案1】:

    filters['q'] 是一个 athletic,bohemian 字符串。 __in 查找需要一个列表或元组。

    query = filters['q'].split(',')
    

    【讨论】:

      猜你喜欢
      • 2013-07-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-16
      • 2020-02-12
      • 2014-07-22
      • 2023-04-08
      • 2012-12-01
      相关资源
      最近更新 更多