[Answered ]-To know the number of objects being serialized at that time. DRF

1πŸ‘

In your serializer, you can override the __new__ and __init__ magic methods like below:

class MySerializer(serializer.ModelSerializer):
        def __new__(cls, *args, **kwargs):
            kwargs.update({"has_many": kwargs.get("many", False)})
        
        def __init__(self, *args, **kwargs):
           super().__init__(*args, **kwargs)
           has_many = self.context["has_many"]

So, while you are serializing your data, you can anytime check if the serializer has been instantiated with the many=True/False and, based on that, do what needs to be done.

πŸ‘€xarhsasi

0πŸ‘

def __init__(self, *args, **kwargs):
       super().__init__(*args, **kwargs)
       request = kwargs['context']['request']
       has_many = True if not request.parser_context["kwargs"].get('pk', None) else False

This is the workaround I have created. But not perfect. But does the job. If someone has a better answer which is working. Please share here.

πŸ‘€Vishnu T

Leave a comment