Django Tastypie不使用ManyToManyField更新资源 [英] Django Tastypie not Updating Resource with ManyToManyField

查看:142
本文介绍了Django Tastypie不使用ManyToManyField更新资源的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么我的资源与ManyToManyField更新与此PUT请求?

Why doesn't my resource with a ManyToManyField update with this PUT request?

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提供了这种交换:

A get on the OrganizationResource gives this exchange:

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字段POST json错误,但是我没有在我的ManyToMany关系中使用through属性。

This is very similar to django tastypie manytomany field POST json error, but I am not using a through attribute on my ManyToMany relationship.

推荐答案

问题证明是验证方法。使用FormValidation意味着像/ api / v1 / organizations / 1 /这样的uri不会作为Django ORM的ForeignKey验证。使用自定义验证来修正问题。

The problem turned out to be the validation method. Using FormValidation means that a uri like /api/v1/organizations/1/ won't validate as a ForeignKey for the Django ORM. Using a custom validation instead fixes the issue.

许多Bothans都死于为我们提供这些信息。

Many Bothans died to bring us this information.

这篇关于Django Tastypie不使用ManyToManyField更新资源的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆