因此,我尝试将我的位置过滤网址设为api/v1/labels/?brand_location=Australia
,以过滤仅使用澳大利亚品牌的品牌,但仍会收到错误消息:
{"error": "Invalid resource lookup data provided (mismatched type)."}
但是当使用api/v1/labels/?brand_location/=Australia
时它可以运行,但只过滤澳大利亚的位置,它会返回完全响应而不排除位置。
所以我的问题是:
我的代码如下:
的 Models.py
class Brand(models.Model):
brand_location = models.ForeignKey('Location', null=True, blank=True, default="")
class Location(models.Model):
state_or_country = models.CharField(unique=True, max_length=200, blank=True, default="", verbose_name=_('Location'),
api.py
class LocationResource(ModelResource):
class Meta:
excludes = ['modified', 'id', 'created']
queryset = Location.objects.all()
resource_name = 'locations'
class LabelResource(ModelResource):
brand_location = fields.ForeignKey(LocationResource, 'brand_location', full=True)
class Meta:
filtering = {
"brand_location": ALL
}
queryset = Brand.objects.all()
resource_name = 'labels'
Snippet JSON响应
{
"labels": [
{
"brand_location": {
"state_or_country": "Australia"
}
}
],
"meta": {
"limit": 6,
"next": "/unlabel-network/unlabel-network-api/v1/labels/?limit=6&brand_location%2F=Australia&offset=6",
"offset": 0,
"previous": null,
"total_count": 128
}
}
答案 0 :(得分:0)
api/v1/labels/?brand_location=Australia
查找Location.id=Australia
。
允许过滤更深:
filtering = {
"brand_location": ALL_WITH_RELATIONS
}
并查找state_or_country
字段:
api/v1/labels/?brand_location__state_or_country=Australia
答案 1 :(得分:0)
我只需要将filtering
添加到我的LocationResource
然后将ALL_WITH_RELATIONS
添加到我的LabelResource
class LocationResource(ModelResource):
class Meta:
excludes = ['modified', 'id', 'created']
queryset = Location.objects.all()
resource_name = 'locations'
filtering = {
"state_or_country": ALL
}
class LabelResource(ModelResource):
brand_location = fields.ForeignKey(LocationResource, 'brand_location', full=True)
class Meta:
filtering = {
"brand_location": ALL,
"brand_location": ALL_WITH_RELATIONS
}
queryset = Brand.objects.all()
resource_name = 'labels'