CHEMSEDDINE HAROUIT
CHEMSEDDINE HAROUIT

Reputation: 352

alter data before update in django rest framework

I've looked around for answers but they say to use update() and it doesn't work for me

After the user updates an entity, I want to change it's data before saving it

N.B: the same thing is done for creating it by overriding the method perform_create() and it works.

Here's my code:

The update view

class CommentUpdateAPIView(generics.UpdateAPIView):
    serializer_class = CommentModelSerializer
    permission_classes  = [permissions.IsAuthenticated]

The serializer

class CommentModelSerializer(serializers.ModelSerializer):
    class Meta:
        model  = Comment   # the model to get fields from
        fields = [      
            'id',
            'user',
            'content',
            'timestamp',
        ]

Thank you

Upvotes: 1

Views: 1008

Answers (1)

CHEMSEDDINE HAROUIT
CHEMSEDDINE HAROUIT

Reputation: 352

Thanks to neverwalkaloner, Here is the solution: in my UpdateAPIView I overrid the method perform_update() of Generic API Views see the docs here GenericAPIView

And finally did this:

class CommentUpdateAPIView(generics.UpdateAPIView):
    serializer_class = CommentModelSerializer
    permission_classes = [permissions.IsAuthenticated]
    queryset = Comment.objects.all()

    def perform_update(self, serializer):
        serializer.save(last_update_time = datetime.now())

Upvotes: 2

Related Questions