DjangoRestFramework - registering a user: difference between UserSerializer.save() and User.objects.create_user()?

后端 未结 1 1369
滥情空心
滥情空心 2020-12-06 03:52

Suppose I want to register a user (I\'m using the User model located in django.contrib.auth.models). Assume this is my serializers.py:

class UserSerializer(s         


        
相关标签:
1条回答
  • 2020-12-06 04:32

    Neither of those is perfect. But View A looks promising.

    • View A is a good start, but it is incomplete solution. Because User creation is not simply User.save, but rather you have to call User.create_user method.
    • View B is the correct way to create user by calling User.create_user, however, the views contains a logic which should actually be abstracted within the Serializer.save() method.

    To solve this, you have to change the behavior of Serializer.save() method. Looking at the documentation, Serializer.save(), will call either Serializer.create() or Serializer.update().

    In summary, we have to override the Serializer.create() for user creation and use View A.

    # File: serializers.py
    class UserSerializer(serializers.ModelSerializer):
        class Meta:
            model = User
    
        def create(self, validated_data):
            user = User.objects.create_user(
                email = validated_data['email'],
                username = validated_data['username'],
                password = validated_data['password'],
            )
            return user
    
    0 讨论(0)
提交回复
热议问题