Categories
Python Answers

How to pass extra arguments to serializer Class in Python Django Rest Framework?

Spread the love

Sometimes, we want to pass extra arguments to serializer Class in Python Django Rest Framework.

In this article, we’ll look at how to pass extra arguments to serializer Class in Python Django Rest Framework.

How to pass extra arguments to serializer Class in Python Django Rest Framework?

To pass extra arguments to serializer Class in Python Django Rest Framework, we set the context argument to a dict with the values we want to pass to the serializer.

For instance, we write

my_objects = MyModelSerializer(
    input_collection, 
    many=True, 
    context={'user_id': request.user.id}
).data

to create a MyModelSerializer by calling MyModelSerializer with the context argument set to a dict.

Then in our serializer class, we write

class MyModelSerializer(serializers.ModelSerializer):
    #...

    is_my_object = serializers.SerializerMethodField('_is_my_find')
    #...

    def _is_my_find(self, obj):
        user_id = self.context.get("user_id")
        if user_id:
            return user_id in obj.my_objects.values_list("user_id", flat=True)
        return False

to get the context values with self.context.get.

Conclusion

To pass extra arguments to serializer Class in Python Django Rest Framework, we set the context argument to a dict with the values we want to pass to the serializer.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *