mr_stack
mr_stack

Reputation: 11

Django Rest Framework Serializer Method Calling

I'm new at Django Rest Framework and I wonder how methods create and update are called inside a ModelSerializer Class.

What I understand is that create and update methods are automatically triggered when a POST or PUT request is sent. Is there a way to call a new function, like say_hello()?

Here's an example. I want to call method say_hello() when I hit a PUT Request

    class UserSerializer(serializers.ModelSerializer):
        """Serializer for the users object"""
    
        class Meta:
            model = User
            fields = "__all__"
    
        def create(self, validated_data):
            """Create a new user with encrypted password and return it"""
            return get_user_model().objects.create_user(**validated_data)
    
        def update(self, instance, validated_data):
            """Update an user, setting the password and return it"""
            password = validated_data.pop('password', None)
            user = super().update(instance, validated_data)
    
            if password:
                user.set_password(password)
                user.save()
    
            return user
    
        def say_hello(self, validated_data):
            print(validated_data)
            return "Hello you"

Upvotes: 1

Views: 2173

Answers (1)

LukasKlement
LukasKlement

Reputation: 527

To call a different method than the update method, you need to overwrite your serializer's def save() method:

def save(self, **kwargs):
    validated_data = [
        {**attrs, **kwargs} for attrs in self.validated_data
    ]

    if self.instance is not None:
        self.instance = self.say_hello(self.instance, validated_data)
        assert self.instance is not None, (
            '`update()` did not return an object instance.'
        )
    else:
        self.instance = self.create(validated_data)
        assert self.instance is not None, (
            '`create()` did not return an object instance.'
        )

    return self.instance

You can check out the Django Rest Framework default implementation here.

But what you rather might want to do, is to modify your ViewSet, by overwriting the def perform_update() method:

def perform_update(self, serializer):
    serializer.say_hello()

Upvotes: 1

Related Questions