当使用django的注释来获取“分组依据”时,它会返回没有PK的对象。由于按字段分组,汇总其他字段并获得单行PK ID毫无意义。
我想我在好吃的地方做错了。但是我从文档中看不到一种进行分组的方法。
因此,我已将queryparam“ groupby”添加到我的自定义资源类中。在“ apply_filters”中,我让asteapie做其通常的事情,然后我介入并应用一个Django“ group by”:
return q.values('type').annotate(*(Sum(x) for x in fields_to_aggregate)).order_by()
这将返回一个对象的Queryset,该对象只有“类型”字段和正确汇总的字段。
我从好吃的东西得到的错误是:
Traceback (most recent call last):
File "/usr/local/lib/python3.6/dist-packages/tastypie/resources.py", line 228, in wrapper
response = callback(request, *args, **kwargs)
File "/usr/local/lib/python3.6/dist-packages/tastypie/resources.py", line 468, in dispatch_list
return self.dispatch('list', request, **kwargs)
File "/usr/local/lib/python3.6/dist-packages/tastypie/resources.py", line 500, in dispatch
response = method(request, **kwargs)
File "/srv/attrib-backend/backend/api/utils.py", line 69, in get_list
for obj in to_be_serialized[self._meta.collection_name]
File "/srv/attrib-backend/backend/api/utils.py", line 69, in <listcomp>
for obj in to_be_serialized[self._meta.collection_name]
File "/srv/attrib-backend/backend/api/utils.py", line 114, in full_dehydrate
data[field_name] = method(bundle)
File "/usr/local/lib/python3.6/dist-packages/tastypie/resources.py", line 1093, in dehydrate_resource_uri
return self.get_resource_uri(bundle)
File "/usr/local/lib/python3.6/dist-packages/tastypie/resources.py", line 837, in get_resource_uri
return self._build_reverse_url(url_name, kwargs=self.resource_uri_kwargs(bundle_or_obj))
File "/usr/local/lib/python3.6/dist-packages/tastypie/resources.py", line 816, in resource_uri_kwargs
kwargs.update(self.detail_uri_kwargs(bundle_or_obj))
File "/usr/local/lib/python3.6/dist-packages/tastypie/resources.py", line 793, 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'
我尝试将“ pk”添加到values()函数,但是仍然出现此错误。另外,返回聚合中的行ID对我来说没有意义。
我可以看到它正在尝试向对象添加“ resource_uri”,有没有办法关闭/禁用resource_uri生成?
就像我说的那样,在聚合时具有ID概念是没有意义的。
我认为我的问题源于必须使用queryset.values()通过聚合获取Django的分组。但是对象返回了,所有字段styrepie都没有“看”为属性。看到以下错误:
"The object
{
type': 'My Type X',
'field_one__sum': 4,
'field_two__sum': Decimal('1045.76'),
}
has an empty attribute 'type' and doesn't allow a default or null value."
感谢您的帮助或指示!