5

我正在尝试使用 Django Rest 框架创建自定义用户。我已经到了可以创建普通用户的地步,但我不确定如何将其扩展到自定义用户模型。

模型.py:

from django.db import models
from django.contrib.postgres.fields import ArrayField
from django.contrib.auth.models import User


class UserProfile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    languages = ArrayField(models.CharField(max_length=30, blank=True))

序列化程序.py:

from rest_framework import serializers
from django.contrib.auth.models import User


class UserSerializer(serializers.ModelSerializer):
    password = serializers.CharField(write_only=True)

    class Meta:
        model = User
        fields = ('first_name', 'last_name', 'email', 'username', 'password')

    def create(self, validated_data, instance=None):
        user = super(UserSerializer, self).create(validated_data)
        user.set_password(validated_data['password'])
        user.save()
        return user

视图.py:

@api_view(['POST'])
@permission_classes((AllowAny,))
def create_user(request):
    serialized = UserSerializer(data=request.data)
    if serialized.is_valid():
        serialized.save()
        return Response(serialized.data, status=status.HTTP_201_CREATED)
    else:
        return Response(serialized._errors, status=status.HTTP_400_BAD_REQUEST)

如何将languages字段扩展UserSerializer到可以处理它的位置?signal每次创建 a 时user创建一个然后userprofile自动创建一个会更好吗?

4

1 回答 1

4

您可以通过两种方式完成此操作,或者通过创建配置文件序列化程序或不使用它。使用串行器,

class UserProfileSerializer(serializers.ModelSerializer):
    languages = serializers.ListField(child=serializers.CharField(max_length=30, allow_blank=True))

    class Meta:
        model = UserProfile
        fields = ('languages',)

class UserSerializer(serializers.ModelSerializer):
    password = serializers.CharField(write_only=True)
    userprofile = UserProfileSerializer(required=False)

    class Meta:
        model = User
        fields = ('first_name', 'last_name', 'email', 'username', 'password', 'userprofile')


    def create(self, validated_data, instance=None):
        profile_data = validated_data.pop('userprofile')
        user = User.objects.create(**validated_data)
        user.set_password(validated_data['password'])
        user.save()
        UserProfile.objects.update_or_create(user=user,**profile_data)
        return user

没有配置文件序列化程序

class UserSerializer(serializers.ModelSerializer):
    password = serializers.CharField(write_only=True)
    languages = serializers.ListField(child=serializers.CharField(max_length=30, allow_blank=True), source="userprofile.languages")

    class Meta:
        model = User
        fields = ('first_name', 'last_name', 'email', 'username', 'password', 'lanugages')


    def create(self, validated_data, instance=None):
        profile_data = validated_data.pop('userprofile')
        user = User.objects.create(**validated_data)
        user.set_password(validated_data['password'])
        user.save()
        UserProfile.objects.update_or_create(user=user,**profile_data)
        return user
于 2017-12-07T09:48:26.430 回答