【问题标题】:Invalid resource lookup data provided (mismatched type)提供的资源查找数据无效(类型不匹配)
【发布时间】:2016-08-07 18:20:10
【问题描述】:

所以我试图将我的位置过滤器网址设置为 api/v1/labels/?brand_location=Australia 以过滤仅包含澳大利亚品牌的品牌返回但不断收到错误消息:

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

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

所以我的问题是:

  1. 如何删除尾部斜杠?并让它过滤仅澳大利亚的位置
  2. 这是解决此问题的正确方法吗?在 django sweetpie 中使用外键时?

我的代码如下:

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'

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

【问题讨论】:

    标签: django tastypie


    【解决方案1】:

    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
    

    【讨论】:

    • 这是我在使用您放置的上述网址时遇到的新错误:{"error": "Lookups are not allowed in the 'brand_location' field."}跨度>
    【解决方案2】:

    我只需要将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'
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-03-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多