1

为什么我的具有 ManyToManyField 的资源不使用此 PUT 请求更新?

curl --dump-header - -H "Content-Type: application/json" -X PUT --data '{"uuid":"blah","pass_token":"blah","favorites": ["/api/v1/organizations/1/"]}' http://localhost:8000/api/v1/devices/2/

我得到这个回应:

HTTP/1.0 400 BAD REQUEST
Date: Wed, 11 Jul 2012 22:21:15 GMT
Server: WSGIServer/0.1 Python/2.7.2
Content-Type: application/json; charset=utf-8

{"favorites": ["\"/api/v1/organizations/1/\" is not a valid value for a primary key."]}

这是我的资源:

class OrganizationResource(ModelResource):
    parent_org = fields.ForeignKey('self','parent_org',null=True, full=True,blank=True)

    class Meta:
        allowed_methods = ['get',]
        authentication = APIAuthentication()
        fields = ['name','org_type','parent_org']
        filtering = {
            'name': ALL,
            'org_type': ALL,
            'parent_org': ALL_WITH_RELATIONS,
        }
        ordering = ['name',]
        queryset = Organization.objects.all()
        resource_name = 'organizations'

class DeviceResource(ModelResource):
    favorites = fields.ManyToManyField(OrganizationResource,'favorites',null=True,full=True)

    class Meta:
        allowed_methods = ['get','patch','post','put',]
        authentication = APIAuthentication()
        authorization = APIAuthorization()
        fields = ['uuid',]
        filtering = {
            'uuid': ALL,
        }
        queryset = Device.objects.all()
        resource_name = 'devices'
        validation = FormValidation(form_class=DeviceRegistrationForm)

获取 OrganizationResource 提供了这种交换:

curl --dump-header - -H "Content-Type: application/json" -X GET http://localhost:8000/api/v1/organizations/1/

HTTP/1.0 200 OK
Date: Wed, 11 Jul 2012 22:38:30 GMT
Server: WSGIServer/0.1 Python/2.7.2
Content-Type: application/json; charset=utf-8

{"name": "name", "org_type": "org_type", "parent_org": null, "resource_uri": "/api/v1/organizations/1/"}

这与django tastepie manytomany field POST json error非常相似,但我没有在我的 ManyToMany 关系上使用 through 属性。

4

2 回答 2

7

问题原来是验证方法。使用 FormValidation 意味着像 /api/v1/organizations/1/ 这样的 uri 不会验证为 Django ORM 的 ForeignKey。改用自定义验证可以解决此问题。

许多博萨人为给我们带来了这些信息而死。

于 2012-07-16T17:59:29.990 回答
2

看起来你既定ManyToManyFieldDeviceResourceForiegnKeyOrganizationResourcefull=True

因此,当执行 PUT Tastypie 时,期望给它一个完整的对象,或者至少是一个带有 resource_uri 的“空白”对象。

尝试使用指定的 resource_uri 而不是仅 uri 发送对象本身,即: {"resource_uri" : "/api/v1/organizations/1/"}而不是"/api/v1/organizations/1/"

curl --dump-header - -H "Content-Type: application/json" -X PUT --data '{"uuid":"blah","pass_token":"blah","favorites": [{"resource_uri" : "/api/v1/organizations/1/"}]}' http://localhost:8000/api/v1/devices/2/
于 2012-07-12T01:00:59.927 回答