我当前聚合了一个查询,以获得端点中使用的字符串的唯一列表。到目前为止,获取的数据如下所示:
{
"data": [
"Beige",
"Grey",
...
]
}
然而,我正在尝试这样做:
{
"data": [
{
name: "Beige",
count: 7
},
{
name: "Grey",
count: 3
},
...
]
}
其中count是值在datbase中出现的次数
目前,我的视图集的结构如下:
class ProductFiltersByCategory(APIView):
"""
This viewset takes the category parameter from the url and returns related product filters
"""
def get(self, request, *args, **kwargs):
"""
Gets parameter in urls and aggregated filtered result
"""
category = self.kwargs['category']
aggregated_result = Product.objects.filter(
category__parent__name__iexact=category,
status='available'
).distinct().aggregate(data=ArrayAgg('colors__name', distinct=True))
return Response(aggregated_result)
如何制作我想要的键值对结构,以及如何计算每种“颜色”
您可以使用集合库中的^{} 来计算值
您可以尝试以下方法:
可以使用^{} 执行此操作:
样本输出:
您可以使用
.values()
按类别注释每个类别和组的Count
。由于您的关系涉及多对多字段,您可能只想查询颜色模型,而不是产品模型相关问题 更多 >
编程相关推荐