Django tastype未使用ManyToManyField更新资源

2024-05-14 15:49:50 发布

您现在位置:Python中文网/ 问答频道 /正文

为什么我的资源和一个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/

我得到的答复是:

^{pr2}$

以下是我的资源:

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 tastypie manytomany field POST json error非常相似,但我没有在manytomy关系中使用through属性。在


Tags: nameorgapijsontruefieldsapplicationtype
2条回答

问题出在验证方法上。使用FormValidation意味着像/api/v1/organizations/1/这样的uri不会作为Django ORM的ForeignKey进行验证。使用自定义验证可以解决此问题。在

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

看起来您将DeviceResource中的ManyToManyField和{}中的{}都设置为full=True。在

因此,当执行PUT tastype时,它期望得到一个完整的对象,或者至少是一个具有resource\u uri的“blank”对象。在

尝试使用指定的resource\u uri而不仅仅是uri来发送对象本身,例如: {"resource_uri" : "/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/

相关问题 更多 >

    热门问题