【发布时间】: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"
]
}
【问题讨论】: