Django 'NoneType' object 没有属性 'obj'

Django 'NoneType' object has no attribute 'obj'

我知道有几个 post 关于这个非常相同的问题,但解决方案是在代码中出现的一些我无法弄清楚的错误中找到的。所以我 post 把我到目前为止写的写在这里,希望能得到你的帮助。 我有一个 class 节点,当我执行 POST 时出现标题中所述的错误。 这是我的代码:

class NodeResource(ModelResource):

class Meta:
    queryset = api.models.Node.objects.all()
    resource_name = _Helpers.node_resource_name
    always_return_data = True

    # Allow retrieving large quantities of nodes at once.
    limit = 250
    max_limit = 0

    filtering = {'name', 'is_ulg', 'latitude', 'longitude'}
    allowed_methods = ['get', 'post']
    authentication = Authentication()
    authorization = Authorization()

def obj_create(self, bundle, **kwargs):
    node = api.models.Node(name=bundle.data['name'],
                           is_ulg=bundle.data['is_ulg'],
                           latitude=bundle.data.get("latitude"),
                           longitude=bundle.data.get("longitude"))
    node.save()

模型如下:

class Node(models.Model):
"""
Represents a node in the graph.
"""
name = models.CharField(max_length=255)
is_ulg = models.BooleanField(default=False, verbose_name='Is this node a member of the ULg?')

latitude = models.FloatField()
longitude = models.FloatField()

def __str__(self):
    return self.name

class Meta:
    ordering = ['name']
    unique_together = ("latitude", "longitude") 

当我使用以下 json

执行 post 时
{"name":"Node name","latitude": "2.4567", "longitude":"2.345", "is_ulg":false}

节点创建正确,但总是出现标题中的错误。完整错误如下:

{"error_message":"'NoneType' object has no attribute 'obj'","traceback":"Traceback (most recent call last):\n\n  File \"\/usr\/lib\/python2.7\/site-packages\/tastypie\/resources.py\", line 202, in wrapper\n    response = callback(request, *args, **kwargs)\n\n  File \"\/usr\/lib\/python2.7\/site-packages\/tastypie\/resources.py\", line 433, in dispatch_list\n    return self.dispatch('list', request, **kwargs)\n\n  File \"\/usr\/lib\/python2.7\/site-packages\/tastypie\/resources.py\", line 465, in dispatch\n    response = method(request, **kwargs)\n\n  File \"\/usr\/lib\/python2.7\/site-packages\/tastypie\/resources.py\", line 1347, in post_list\n    updated_bundle = self.full_dehydrate(updated_bundle)\n\n  File \"\/usr\/lib\/python2.7\/site-packages\/tastypie\/resources.py\", line 853, in full_dehydrate\n    bundle.data[field_name] = field_object.dehydrate(bundle, for_list=for_list)\n\n  File \"\/usr\/lib\/python2.7\/site-packages\/tastypie\/fields.py\", line 116, in dehydrate\n    current_object = bundle.obj\n\nAttributeError: 'NoneType' object has no attribute 'obj'\n"}

知道我做错了什么吗? 谢谢!

您的 object_create 函数隐含地 returning None,但 Tastypie 期望它 return 一个包。在 docs example.

中查看它是如何实现的

但是,由于您似乎没有使用非 ORM 数据,因此您可以跳过 obj_create 并让 Tastypie 为您创建资源。