Viewset 'create' 在 Django Rest Framework 中自定义赋值

Viewset 'create' custom assign value in Django Rest Framework

想使用输入的电子邮件设置 CustomUser 的用户名,但是在哪里进行自定义分配,在视图中?同时它也收到一个文件。

Models.py

class CustomUser(AbstractUser):
    avatar = models.ImageField(max_length=None, upload_to='avatar', blank=True)

Serializers.py

class CustomUserSerializer(serializers.ModelSerializer):

    class Meta:
        model = CustomUser
        fields = ('id', 'first_name', 'last_name', 'email', 'password', 'avatar', 'groups')

Views.py

class CustomUserViewSet(viewsets.ModelViewSet):

    queryset = CustomUser.objects.all()
    serializer_class = CustomUserSerializer

提前致谢。

@Anzel 所说的可行,但如果您想在 django-rest-framework 中执行此操作,您可以覆盖 [=12= 的 create 方法].喜欢:

class CustomUserSerializer(serializers.ModelSerializer):

    groups = serializers.PrimaryKeyRelatedField(many=True, read_only=True)

    def create(self, validated_data):
        user = CustomUser.objects.create_user(
            username    =validated_data['email'], # HERE
            email       =validated_data['email'],
            password    =validated_data['password'],
            first_name  =validated_data['first_name'], 
            last_name   =validated_data['last_name'],
            avatar      =validated_data['avatar'],
        )

        user.groups = validated_data['groups']
        return user

    class Meta:
       model = CustomUser
       fields = (
           'id', 
           'first_name', 
           'last_name', 
           'email', 
           'password', 
           'avatar', 
           'groups'
       )