Django的Tastypie不ManyToManyField更新资源(Django Tastypi

2019-06-26 06:01发布

为什么我用这个PUT请求ManyToManyField更新资源?

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一个GET给出了这样的对话:

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 tastypie多对多后场JSON的错误 ,但我没有通过我的多对多关系属性使用。

Answer 1:

原来,这个问题是验证方法。 使用FormValidation意味着像/ API / V1 /组织/ 1 /一个URI将不会验证作为Django的ORM一个ForeignKey。 使用自定义的确认,而不是修复该问题。

博萨许多死给我们带来这样的信息。



Answer 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/


文章来源: Django Tastypie not Updating Resource with ManyToManyField