Accessing Django Serializer Context

Hi everyone,

I’ve been having a problem with a serializer. I’m using DRF and trying to do some calculations, save the analysis inside the serializer context, and then use that data in some methods that implement data retrieval for a SerializerMethodField. The problem is that the context key I used to store the data is empty when I try to use it to retrieve the data. It’s a ORM query and I don’t want to repeat it for each field.

This is an excerpt of the code:

class LinkClaimListPipelineSerializer(serializers.ModelSerializer):
target_page = serializers.SerializerMethodField()

def __init__(self, *args, **kwargs):
    super().__init__(*args, **kwargs)
    qs = LinkClaimPoint.objects.filter(
        link_claim_id__in=[claim.pk for claim in self.instance]
    )
    points = qs.values('name').annotate(total_value=Sum('value'))
    self.context['points'] = {point['name']:point['total_value'] for point in points}

I have had no luck trying to figure it out. Some sources I found mentioned implementing get_context() and get_serializer_context() methods that return self.context, but that did not work. I also asked the ChatGPT thing and gave it a section of the code and that did not help either.

Any help would be highly appreciated!