我知道有一些帖子关于这个同样的问题,但解决方案是在代码中发现的一些我无法弄清楚的错误。所以我在这里发布了迄今为止我所写的内容,希望得到你的帮助。 我有一个类Node,当我执行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):\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"}
知道我做错了什么吗? 谢谢!
答案 0 :(得分:3)
您的object_create
函数隐式返回None
,但Tastypie希望它返回一个包。请参阅docs example。
但是,由于您似乎并未使用非ORM数据,因此您可以跳过obj_create
并让Tastypie为您创建资源。