提供的资源查找数据无效(类型不匹配)

时间:2016-08-07 18:20:11

标签: django tastypie

因此,我尝试将我的位置过滤网址设为api/v1/labels/?brand_location=Australia,以过滤仅使用澳大利亚品牌的品牌,但仍会收到错误消息:

{"error": "Invalid resource lookup data provided (mismatched type)."}

但是当使用api/v1/labels/?brand_location/=Australia时它可以运行,但只过滤澳大利亚的位置,它会返回完全响应而不排除位置。

所以我的问题是:

  1. 如何删除斜杠?并让它过滤仅限澳大利亚的地点
  2. 这是正确的方法吗?使用带有django tastypie的外键吗?
  3. 我的代码如下:

    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
      }
    }
    

2 个答案:

答案 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'