Search code examples
djangoserializationdjango-rest-framework

Can someone explain to me what "data = validated_data.copy()" means?


I wonder why the create method does not process the data directly but has to copy it into data and then process it indirectly, while the returned result is also the processed user.

class UserSerializer(serializers.ModelSerializer):
    alumni = AlumniSerializer()
    
    def to_representation(self, instance):
        req = super().to_representation(instance)
        if instance.avatar:
            req['avatar'] = instance.avatar.url
            
        if instance.cover:
            req['cover'] = instance.cover.url
        
        return req
    
    def create(self, validated_data):
        data = validated_data.copy()
        user = User(**data)
        user.set_password(user.password)
        user.save()
        
        return user
    
    class Meta:
        model = User
        fields = ['id', 'first_name', 'last_name', 'username', 'password', 'email', 'avatar', 'cover', 'alumni']
        extra_kwargs = {
            'password': {
                'write_only': True
            }
        }

Solution

  • The reason of copying the validated_data into a new variable is to ensure that the original validated_data remains unmodified to maintain data integrity and prevent unintended side effects.

    So if you change the data while creating a user it wont effect the validated data of the serializer