1

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"
3
  • 1
    You can call the say_hello(...) method from the update() method, right? Commented Nov 15, 2020 at 3:40
  • Sure, but how can I call a different method instead update, create? Commented Nov 15, 2020 at 13:44
  • This happens in the views. It really dipense what kind of view you are using. In generic views you can change this behavior in perform_create(self, serializer) and perform_update(self, serializer). Commented Nov 15, 2020 at 14:00

1 Answer 1

1

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()
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.