Django 'NoneType' 对象没有属性 'obj'



我知道有一些关于这个问题的帖子,但解决方案是在我无法弄清楚的代码中出现的一些错误中找到的。所以我在这里发布我到目前为止写的东西,希望得到你的帮助。我有一个类节点,当我执行 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执行帖子时

{"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):nn  File "/usr/lib/python2.7/site-packages/tastypie/resources.py", line 202, in wrappern    response = callback(request, *args, **kwargs)nn  File "/usr/lib/python2.7/site-packages/tastypie/resources.py", line 433, in dispatch_listn    return self.dispatch('list', request, **kwargs)nn  File "/usr/lib/python2.7/site-packages/tastypie/resources.py", line 465, in dispatchn    response = method(request, **kwargs)nn  File "/usr/lib/python2.7/site-packages/tastypie/resources.py", line 1347, in post_listn    updated_bundle = self.full_dehydrate(updated_bundle)nn  File "/usr/lib/python2.7/site-packages/tastypie/resources.py", line 853, in full_dehydraten    bundle.data[field_name] = field_object.dehydrate(bundle, for_list=for_list)nn  File "/usr/lib/python2.7/site-packages/tastypie/fields.py", line 116, in dehydraten    current_object = bundle.objnnAttributeError: 'NoneType' object has no attribute 'obj'n"}

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

您的object_create函数隐式返回None,但 Tastypie 希望它返回一个捆绑包。在文档示例中查看它是如何实现的。

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

相关内容

  • 没有找到相关文章

最新更新