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

眉间皱痕 提交于 2019-11-27 22:38:18

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
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!