Django的Tastypie,多对多保存错误(Django Tastypie, ManyToMan

2019-06-25 22:29发布

当我保存的项目,通过tastypie API我有一个问题。 (POST方法)

这是我api.py代码。

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()

当IM POST数据,保存成功,但给我的错误。

{"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"}

当我加入“回包”线hydrate_m2m,M2M储蓄不成功(空白),仍然给我的错误是这样的。

{"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,返回的错误是:

{"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"}

我认为URL提供的“1”是用户ID。

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

顺便说一句,我不知道英语非常好,对不起那个。

Answer 1:

我敢肯定,那您发布的用户资源为逗号分隔的ID。 这不是tastypie默认处理与资源的方式。 你应该张贴的URL列表,指向相关资源,你的情况 - 水木清华像“/ API / V1 /用户/ 1”。

另外,您可以hydrate_m2m改为hydrate_users。 在你的资源,尝试将其从URL字符串转换为相关资源的实例各个领域通用hydrate_m2m迭代(这就是为什么你对“提供的网址”的错误)。 对于hydrate_users的代码可能是这样的:

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

希望这可以帮助

编辑:有利于去除拉姆达int卡森建议



文章来源: Django Tastypie, ManyToMany Saving Error