Django Tastypie,多对多保存错误 [英] Django Tastypie, ManyToMany Saving Error

查看:34
本文介绍了Django Tastypie,多对多保存错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在通过tastypie api保存项目时遇到问题.(POST方法)

i got a problem when i'm saving an item, via tastypie api. (POST method)

这是我的 api.py 代码.

Here is my api.py code.

from tastypie.resources import ModelResource, ALL, ALL_WITH_RELATIONS
from tastypie.authorization import DjangoAuthorization
from tastypie.authentication import BasicAuthentication
from tastypie import fields
from apps.clients.models import Client
from django.contrib.auth.models import User

class ClientAPI(ModelResource):
    users = fields.ToManyField('apps.clients.api.ClientUserAPI', 'users',related_name='entry',full=True)


    class Meta:
        queryset = Client.objects.all()
        resource_name="clients"
        authentication = BasicAuthentication()
        authorization = DjangoAuthorization()
        filtering={
            "users":ALL
        }

    def hydrate_m2m(self,bundle):
        if bundle.data.get("users"):
            for user_id in bundle.data["users"]:
                new_user = User.objects.get(id=user_id)
                bundle.obj.users.add(new_user)


class ClientUserAPI(ModelResource):
    class Meta:
        queryset = User.objects.all()
        resource_name = 'users'
        fields = ['username', 'first_name', 'last_name', 'last_login']
        authentication = BasicAuthentication()
        authorization = DjangoAuthorization()

当我 POST 数据时,保存成功,但出现错误.

when im POST data, saving is successful, but gives me error.

{"error_message": "'NoneType' object has no attribute 'obj'", "traceback": "Traceback (most recent call last):\n\n File \"/Library/Python/2.7/site-packages/tastypie/resources.py\", line 192, in wrapper\n response = callback(request, *args, **kwargs)\n\n File \"/Library/Python/2.7/site-packages/tastypie/resources.py\", line 397, in dispatch_list\n return self.dispatch('list', request, **kwargs)\n\n File \"/Library/Python/2.7/site-packages/tastypie/resources.py\", line 427, in dispatch\n response = method(request, **kwargs)\n\n File \"/Library/Python/2.7/site-packages/tastypie/resources.py\", line 1165, in post_list\n updated_bundle = self.obj_create(bundle, request=request, **self.remove_api_resource_names(kwargs))\n\n File \"/Library/Python/2.7/site-packages/tastypie/resources.py\", line 1784, in obj_create\n self.save_m2m(m2m_bundle)\n\n File \"/Library/Python/2.7/site-packages/tastypie/resources.py\", line 1942, in save_m2m\n related_mngr = getattr(bundle.obj, field_object.attribute)\n\nAttributeError: 'NoneType' object has no attribute 'obj'\n"}

当我将return bundle"行添加到 hydrate_m2m 时,m2m 保存不成功(空白),仍然给我这样的错误.

when i'm add "return bundle" line to hydrate_m2m, m2m saving is not successful (blank), still gives me error like this.

{"error_message": "'str' object has no attribute 'obj'", "traceback": "Traceback (most recent call last):\n\n File \"/Library/Python/2.7/site-packages/tastypie/resources.py\", line 192, in wrapper\n response = callback(request, *args, **kwargs)\n\n File \"/Library/Python/2.7/site-packages/tastypie/resources.py\", line 397, in dispatch_list\n return self.dispatch('list', request, **kwargs)\n\n File \"/Library/Python/2.7/site-packages/tastypie/resources.py\", line 427, in dispatch\n response = method(request, **kwargs)\n\n File \"/Library/Python/2.7/site-packages/tastypie/resources.py\", line 1165, in post_list\n updated_bundle = self.obj_create(bundle, request=request, **self.remove_api_resource_names(kwargs))\n\n File \"/Library/Python/2.7/site-packages/tastypie/resources.py\", line 1784, in obj_create\n self.save_m2m(m2m_bundle)\n\n File \"/Library/Python/2.7/site-packages/tastypie/resources.py\", line 1951, in save_m2m\n related_bundle.obj.save()\n\nAttributeError: 'str' object has no attribute 'obj'\n"}

当我从代码中删除 hydrate_m2m 时,返回错误是:

when i'm deleting hydrate_m2m from code, returning error is:

{"error_message": "The URL provided '1' was not a link to a valid resource.", "traceback": "Traceback (most recent call last):\n\n File \"/Library/Python/2.7/site-packages/tastypie/resources.py\", line 192, in wrapper\n response = callback(request, *args, **kwargs)\n\n File \"/Library/Python/2.7/site-packages/tastypie/resources.py\", line 397, in dispatch_list\n return self.dispatch('list', request, **kwargs)\n\n File \"/Library/Python/2.7/site-packages/tastypie/resources.py\", line 427, in dispatch\n response = method(request, **kwargs)\n\n File \"/Library/Python/2.7/site-packages/tastypie/resources.py\", line 1165, in post_list\n updated_bundle = self.obj_create(bundle, request=request, **self.remove_api_resource_names(kwargs))\n\n File \"/Library/Python/2.7/site-packages/tastypie/resources.py\", line 1783, in obj_create\n m2m_bundle = self.hydrate_m2m(bundle)\n\n File \"/Library/Python/2.7/site-packages/tastypie/resources.py\", line 743, in hydrate_m2m\n bundle.data[field_name] = field_object.hydrate_m2m(bundle)\n\n File \"/Library/Python/2.7/site-packages/tastypie/fields.py\", line 742, in hydrate_m2m\n m2m_hydrated.append(self.build_related_resource(value, **kwargs))\n\n File \"/Library/Python/2.7/site-packages/tastypie/fields.py\", line 588, in build_related_resource\n return self.resource_from_uri(self.fk_resource, value, **kwargs)\n\n File \"/Library/Python/2.7/site-packages/tastypie/fields.py\", line 522, in resource_from_uri\n obj = fk_resource.get_via_uri(uri, request=request)\n\n File \"/Library/Python/2.7/site-packages/tastypie/resources.py\", line 636, in get_via_uri\n raise NotFound(\"The URL provided '%s' was not a link to a valid resource.\" % uri)\n\nNotFound: The URL provided '1' was not a link to a valid resource.\n"}

我认为提供1"的 URL 是用户 ID.

i think URL provided "1" is user id.

请告诉我.我做错了什么?

Please tell me. What im doing wrong?

顺便说一句,我不太懂英语,很抱歉.

btw, i dont know english very well, sorry for that.

推荐答案

我很确定,您正在以逗号分隔的 ID 发布用户资源.这不是默认情况下tastypie 处理相关资源的方式.在您的情况下,您应该发布指向相关资源的 url 列表 - 类似于/api/v1/users/1".

I'm pretty sure, that you're posting user resources as comma-separated id's. That's not the way tastypie handles related resources by default. You should post a list of urls, pointing to the related resources, in your case - smth like '/api/v1/users/1'.

或者,您可以将 hydrate_m2m 更改为 hydr_users.通用 hydr_m2m 遍历资源中的每个字段,并尝试将其从 url-string 转换为相关资源的实例(这就是您收到有关提供的 URL"的错误的原因).hydr_users 的代码可能如下所示:

Alternatively you can change hydrate_m2m to hydrate_users. Generic hydrate_m2m iterates over every field in you resource and tries to convert it from url-string to an instance of related resource (that's why you get error about the "provided URL"). The code for hydrate_users might look like this:

def hydrate_users(self, bundle):
    try:
        user_ids = map(int, bundle.data.get('users', []))
    except ValueError:
        raise BadRequest("User ids must be ints") # from tastypie.exceptions
    bundle.data['users'] = User.objects.filter(id__in=user_ids)
    return bundle

希望能帮到你

删除了 lambda 以支持 int,正如 Carson 建议的那样

removed lambda in favour of int as Carson suggested

这篇关于Django Tastypie,多对多保存错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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