在每个聚合值旁边添加计数

2024-09-27 00:22:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我当前聚合了一个查询,以获得端点中使用的字符串的唯一列表。到目前为止,获取的数据如下所示:

{
    "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)

如何制作我想要的键值对结构,以及如何计算每种“颜色”


Tags: andthenameselfdataparametercountresult
3条回答

您可以使用集合库中的^{}来计算值

您可以尝试以下方法:

from collections import Counter

data = get_data_from_endpoint(request)[data]
c = Counter(data)
result = {'data': [{'name': element, 'count': c[element]} for element in c]}

可以使用^{}执行此操作:

from random import choices
from collections import Counter
from pprint import pprint

colours = ['White', 'Yellow', 'Blue', 'Red', 'Green', 'Black', 'Brown', 'Azure', 'Ivory', 'Teal', 'Silver', 'Purple', 'Navy blue', 'Pea green', 'Gray',
           'Orange', 'Maroon', 'Charcoal', 'Aquamarine', 'Coral', 'Fuchsia', 'Wheat', 'Lime', 'Crimson', 'Khaki', 'Hot pink', 'Magenta', 'Olden', 'Plum', 'Olive', 'Cyan']

data = {"data": choices(colours, k=10)}
pprint(data)
newData = {"data": [{"name": k, "count": v} for k,v in Counter(data["data"]).items()]}
pprint(newData)

样本输出:

{'data': ['Coral',
          'Ivory',
          'Red',
          'Crimson',
          'Azure',
          'Ivory',
          'Red',
          'Red',
          'Khaki',
          'Hot pink']}
{'data': [{'count': 1, 'name': 'Coral'},
          {'count': 2, 'name': 'Ivory'},
          {'count': 3, 'name': 'Red'},
          {'count': 1, 'name': 'Crimson'},
          {'count': 1, 'name': 'Azure'},
          {'count': 1, 'name': 'Khaki'},
          {'count': 1, 'name': 'Hot pink'}]}

您可以使用.values()按类别注释每个类别和组的Count。由于您的关系涉及多对多字段,您可能只想查询颜色模型,而不是产品模型

Color.objects.filter(
    product__category__parent__name__iexact=category,
    product__status='available'
).values('name', 'product').annotate(
    colors_count=Count('product', distinct=True)
).values_list('name', 'colors_count')

相关问题 更多 >

    热门问题