我在尝试返回GET请求中的汇总数据时遇到了麻烦-我正在使用django和tastypie。 我可以在Django shell中生成所需的内容:
X.objects.using(“ myDB”)。values(“ some_name”)。annotate(Avg(“ number”))
这是我的模特:
class X(models.Model):
some_name = models.CharField(max_length=128, blank=True, null=True)
other_name = models.CharField(max_length=128, blank=True, null=True)
another_name = models.CharField(max_length=255, blank=True, null=True)
number = models.IntegerField()
class Meta:
managed = False
db_table = 'some_table'
这里的资源:
class XResource(ModelResource):
class Meta:
queryset = X.objects.using("myDB").values("some_name").annotate(Avg("number"))
resource_name = 'myResource'
我正在尝试获得如下响应:
{'meta': {'limit': 20, 'next': None, 'offset': 0, 'previous': None, 'total_count': 5}, 'objects': [{"some_name": "name_1", "number__avg": 100}, {"some_name": "name_2", "number__avg": 200}, {"some_name": "name_3", "number__avg": 300}, {"some_name": "name_4", "number__avg": 400}, {"some_name": "name_5", "number__avg": 500}]}
但是我遇到了这个错误:
{
"error_message": "'dict' object has no attribute 'pk'",
"traceback": "Traceback (most recent call last):\n\n File \"C:\\django\\master\\lib\\site-packages\\tastypie\\resources.py\", line 227, in wrapper\n response = callback(request, *args, **kwargs)\n\n File \"C:\\django\\master\\lib\\site-packages\\tastypie\\resources.py\", line 467, in dispatch_list\n return self.dispatch('list', request, **kwargs)\n\n File \"C:\\django\\master\\lib\\site-packages\\tastypie\\resources.py\", line 499, in dispatch\n response = method(request, **kwargs)\n\n File \"C:\\django\\master\\lib\\site-packages\\tastypie\\resources.py\", line 1364, in get_list\n for obj in to_be_serialized[self._meta.collection_name]\n\n File \"C:\\django\\master\\lib\\site-packages\\tastypie\\resources.py\", line 1364, in <listcomp>\n for obj in to_be_serialized[self._meta.collection_name]\n\n File \"C:\\django\\master\\lib\\site-packages\\tastypie\\resources.py\", line 918, in full_dehydrate\n data[field_name] = method(bundle)\n\n File \"C:\\django\\master\\lib\\site-packages\\tastypie\\resources.py\", line 1092, in dehydrate_resource_uri\n return self.get_resource_uri(bundle)\n\n File \"C:\\django\\master\\lib\\site-packages\\tastypie\\resources.py\", line 836, in get_resource_uri\n return self._build_reverse_url(url_name, kwargs=self.resource_uri_kwargs(bundle_or_obj))\n\n File \"C:\\django\\master\\lib\\site-packages\\tastypie\\resources.py\", line 815, in resource_uri_kwargs\n kwargs.update(self.detail_uri_kwargs(bundle_or_obj))\n\n File \"C:\\django\\master\\lib\\site-packages\\tastypie\\resources.py\", line 792, in detail_uri_kwargs\n kwargs[self._meta.detail_uri_name] = getattr(bundle_or_obj, self._meta.detail_uri_name)\n\nAttributeError: 'dict' object has no attribute 'pk'\n"
}
我尝试使用itertools.groupby解决问题-但我没有得到任何好的结果。
任何建议/提示将不胜感激。
谢谢!