我有这个tastypie资源:
class TagResource_min(ModelResource):
class Meta:
queryset=Question.objects.values('text', 'id')
当我这样做时,我有错误:
{
"error_message": "'dict' object has no attribute 'pk'",
"traceback": "
Traceback (most recent call last):
File \"/home/will/agora/env/lib/python3.5/site-packages/tastypie/resources.py\", line 219, in wrapper
response = callback(request, *args, **kwargs)
File \"/home/will/agora/env/lib/python3.5/site-packages/tastypie/resources.py\", line 450, in dispatch_list
return self.dispatch('list', request, **kwargs)
File \"/home/will/agora/env/lib/python3.5/site-packages/tastypie/resources.py\", line 482, in dispatch
response = method(request, **kwargs)
File \"/home/will/agora/env/lib/python3.5/site-packages/tastypie/resources.py\", line 1340, in get_list
for obj in to_be_serialized[self._meta.collection_name]
File \"/home/will/agora/env/lib/python3.5/site-packages/tastypie/resources.py\", line 1340, in <listcomp>
for obj in to_be_serialized[self._meta.collection_name]
File \"/home/will/agora/env/lib/python3.5/site-packages/tastypie/resources.py\", line 895, in full_dehydrate
data[field_name] = method(bundle)
File \"/home/will/agora/env/lib/python3.5/site-packages/tastypie/resources.py\", line 1068, in dehydrate_resource_uri
return self.get_resource_uri(bundle)
File \"/home/will/agora/env/lib/python3.5/site-packages/tastypie/resources.py\", line 819, in get_resource_uri
return self._build_reverse_url(url_name, kwargs=self.resource_uri_kwargs(bundle_or_obj))
File \"/home/will/agora/env/lib/python3.5/site-packages/tastypie/resources.py\", line 798, in resource_uri_kwargs
kwargs.update(self.detail_uri_kwargs(bundle_or_obj))
File \"/home/will/agora/env/lib/python3.5/site-packages/tastypie/resources.py\", line 775, in detail_uri_kwargs
kwargs[self._meta.detail_uri_name] = getattr(bundle_or_obj, self._meta.detail_uri_name)
AttributeError: 'dict' object has no attribute 'pk'"
}
它所引用的'dict'
必须是Question.objects.values('text', 'id')
获取的查询集。当我登录shell并询问Question.objects.values('text', 'id')
时,我有以下内容:
<QuerySet [{'text': 'Why does capillary action take place?', 'id': 1}, {'text': "If a human brain was connected to a fish's body, how would the humans thoughts change?", 'id': 2},...
使用objects.values()
我做错了什么?如何使用objects.values()
显示新的查询集?
编辑当我使用Question.objects.values()
时,它会返回一个dict
数组,其中没有属性dict.pk
。但是当我Question.objects.all()
时,它返回一个ModelResource
类型的数组,当我调用ModelResource.pk
时,它们都返回一个整数。
这些信息真的没有用......哈哈。因为我确信解决方案在于tastypie或django库。虽然如果我能找到一种方法来附加一个pk来解决我的问题。
答案 0 :(得分:1)
values()
方法返回一个返回字典而不是模型实例的查询集。模型实例具有pk
属性,但字典没有。 Tastypie试图访问dict中的pk
,从而产生错误。您需要使用返回给出模型实例的查询集的方法。
从Django's documentation使用values()
:
当你知道你只需要来自少数可用字段的值时,你将不需要模型实例对象的功能。
在您的情况下,您确实需要模型实例对象pk
属性的功能。
我建议使用Question.objects.all()