Python/Django Rest Framework put same value objects in one list of dictionaries

I want to put the datas to one list of dictionaries if the label value of the objects are the same Just like the example below:

            dataPoints: [
                { x: new Date(2017,0), y: 1000, label:"Austria" },
                { x: new Date(2018,0), y: 1111, label:"Austria" },
                { x: new Date(2019,0), y: 2000,label:"Austria" },
                { x: new Date(2020,0), y: 1224,label:"Austria" },
                { x: new Date(2021,0), y: 4294,label:"Austria" }, 
            ]

For this i did something like this:

class CustomBusinessIntelligenceList(generics.ListAPIView):
    queryset = BusinessIntelligence.objects.all().order_by("-years__year")
    serializer_class = BusinessIntelligenceSerializer
    filter_backends = [DjangoFilterBackend]
    filterset_class = CustomBusinessInteligenceFilter

    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())

        dummy_response = []
        mapping = {}

        for count in range(0, len(queryset)):
            dummy_response.extend([{"x": datetime.datetime(queryset[count].years.year, 1, 1), "y": queryset[count].amount,  "label": queryset[count].countries.name}])


        for d in dummy_response:
            print(d) 

    return Response(dummy_response)

This gave me this response. That i do not want to see:

{
    "x": "2014-01-01T00:00:00",
    "y": "51717.5",
    "label": "Austria"
},

My best attempt was this and this did not give me the response that i wanted:

class CustomBusinessIntelligenceList(generics.ListAPIView):
    queryset = BusinessIntelligence.objects.all().order_by("-years__year")
    serializer_class = BusinessIntelligenceSerializer
    filter_backends = [DjangoFilterBackend]
    filterset_class = CustomBusinessInteligenceFilter

    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())

        dummy_response = []
        mapping = {}
        for count in range(0, len(queryset)):
            dummy_response.extend([{"x": datetime.datetime(queryset[count].years.year, 1, 1), "y": queryset[count].amount,  "label": queryset[count].countries.name}])

        for d in dummy_response:

            try:
                entry = mapping[d[
                    'label']]  # raises KeyError:
                entry['y'].append((d[
                    'y']))  # raises AttributeError: 
                entry['x'].append((d[
                    'x']))  # raises AttributeError:
            except KeyError:
                mapping[d[
                    'label']] = d 
            except AttributeError:
                entry['y'] = [entry['y'], d[
                    'y']] 
                entry['x'] = [entry['x'], d[
                    'x']] 
        return Response(mapping.values())

Response:

{
    "x": [
        "2014-01-01T00:00:00",
        "2012-01-01T00:00:00",
        "2011-01-01T00:00:00",
        "2002-01-01T00:00:00"
    ],
    "y": [
        "51717.5",
        "4900.0",
        "2.5",
        "739.18049"
    ],
    "label": "Austria"
},

Model:

class BusinessIntelligence(models.Model):
    # relations
    countries = models.ForeignKey(
        'core.Country', on_delete=models.CASCADE, related_name='countries_business_intelligence')
    categories = models.ForeignKey('core.Category', on_delete=models.CASCADE,
                               related_name='categories_business_intelligence')
    indicators = models.ForeignKey('core.Indicator', on_delete=models.CASCADE,
                               related_name='indicators_business_intelligence')

    years = models.ForeignKey('core.Years', on_delete=models.CASCADE,
                          related_name='years_business_intelligence')

    # informations
    amount = models.CharField(max_length=255, null=True, blank=True)
    rank = models.IntegerField(default=0)

    # moderations
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    def __str__(self):
        return str(self.countries)

Serializer:

class BusinessIntelligenceSerializer(serializers.ModelSerializer):
    years = serializers.StringRelatedField()
    countries = CountrySerializer()
    class Meta:
        model = BusinessIntelligence
        fields = '__all__'
Back to Top