使用django tastypie

时间:2016-09-01 23:03:59

标签: python django tastypie

我正在使用MultiSelectField在我的django admin中选择多个选项,它为我选择的所有选项的后端中的字段创建一个数组。然后我使用django tastypie's列表字段来确保它是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"
  ]
}

1 个答案:

答案 0 :(得分:0)

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

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