DEV Community

Cover image for Django -> 3 ways to call Serializer
Tehreem Sadat
Tehreem Sadat

Posted on

Django -> 3 ways to call Serializer

Every serializer can be used for both reading and writing operations. The way it is initialized determines the action that it will fulfill. In these terms we can distinguish 3 types of serializers: create, update and retrieve.

Retrieve:

If in your view you want to serialize data that will be transmitted outside of your API, this is how you do it:

def retrieve(self, request, *args, **kwargs):
    instance = self.get_object()
    serializer = ProfileSerializer(instance=instance)
    return Response(serializer.data)
Enter fullscreen mode Exit fullscreen mode

In here you are passing instance (only) as argument so serilaizer will know that it does not need to perform any action. It will simply serialize your data and return it.

Create:

In your create view, where you are saving your data you will define it in a different way:

def create(self, request, *args, **kwargs):
    serializer = ProfileSerializer(data=request.data)
    serializer.is_valid(raise_exception=True)
    serializer.save()
    return Response(serializer.data)
Enter fullscreen mode Exit fullscreen mode

In here you are passing data (only) as argument so serilaizer will know that it needs to invoke all validations and then create method to save our object.

Update:

When updating an instance, you need to provide instance as well as data:

def update(self, request, *args, **kwargs):
    instance = self.get_object()
    serializer = ProfileSerializer(
        instance=instance,
        data=request.data
    )
    serializer.is_valid(raise_exception=True)
    serializer.save()
    return Response(serializer.data)
Enter fullscreen mode Exit fullscreen mode

If you are passing both data and instance as argument, serilaizer will know that it needs to invoke all validations and then update method to update an existing object.

Point to Note:

serializer.save() invokes an appropriate internal method (create/update) based on arguments passed at the time of initialization.

For Retrieve -> You need to pass instance (only)
For Create -> You need to pass data (only)
For Update -> You need to pass both instance and data.

Top comments (0)