Search code examples
djangodjango-rest-frameworkdjango-viewsdjango-serializerdjango-context

Pass context to ModelSerializer field in Django Rest Framework


I am trying to pass a variable from my view to the serializer via context. The Serializer should be able to get the context variable and use it in a field that contains a nested serializer.

Since the nested serializer field cannot be read_only, I cannot use serializerMethodField.

This is how I pass the context to the serializer:

class MyListCreateAPIView(generics.ListCreateAPIView):
    
    # [...]

    def get_serializer_context(self):
        return {
            'request': self.request,
            'format': self.format_kwarg,
            'view': self,
            'asTime': '2021-02-04 16:40:00',   # <-- This is my context variable
        }

This is my serializer:

class MySerializer(serialisers.ModelSerializer):
    child = MyChildSerializer(read_only=False, asTime= ??) # <-- here I want to pass the context variable

    class Meta:
         model = MyModel
         fields = '__all__'

I know that I can access the context variable with self.context.get('asTime') but I can't access self in MySerializer attributes (child). How do I do it?


Solution

  • You could update context of the child on init:

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)        
        self.fields['child'].context.update(self.context)
    

    or you could catch it in for instance to_representation as:

     self.parent.context["asTime"]