Django REST Framework Serializer输出

时间:2017-05-05 07:24:06

标签: django python-2.7 django-rest-framework django-serializer

我是Django和DRF的新手,但我正在尝试使用DRF的Serializer来覆盖djosers的默认用户注册行为。
(djoser =用于用户注册/登录/密码重置等的DRF库。)

我是djosers视图,它使用序列化程序来创建用户对象
def perform_create(self, serializer): user = serializer.save()

我的想法是覆盖此序列化程序以实现以下目标:

  1. 创建用户
  2. 并行创建帐户对象
  3. 登录用户
  4. 在一个回复中将帐户对象与身份验证令一起返回
  5. 最后一点给我带来了麻烦,因为我不知道如何在序列化程序中实现这种自定义行为。我将输入字段设为readonly,因此它们不包含在我的响应中。在save方法中创建用户+帐户对象,登录用户然后返回用户(视图需要)
    如何将创建的帐户对象与创建的令牌字符串序列化为一个响应?

    这是我的序列化程序(简化并从某些内容中删除,但基本上就是这样)

    class UserRegistrationSerializer(serializers.Serializer):
    email = serializers.EmailField(write_only=True)
    # some other fields
    password = serializers.CharField(style={'input_type': 'password'},
                                     write_only=True,
                                     validators=settings.get('PASSWORD_VALIDATORS')
                                     )
    # this should be the output
    account = Account(read_only=True)
    
    def save(self):
        user = User(email=self.validated_data['email'])
        user.set_password(self.validated_data['password'])
        user.save()
    
        account = Account(user=user)
        token = #logging in my user 
    
        return user
    

1 个答案:

答案 0 :(得分:1)

使用它:

class UserRegistrationSerializer(serializers.ModelSerializer):
    email = serializers.EmailField(write_only=True)
    # some other fields
    password = serializers.CharField(
                               style={'input_type': 'password'},
                               write_only=True,
                               validators=settings.get('PASSWORD_VALIDATORS')
                               )
    # make sure you have related_name='account' in your one to one field
    account = AccountSerializer(read_only=True)
    # the token field
    auth_token = TokenSerializer(read_only=True)

    class Meta:
        model = User
        # define fields based on your needs
        fields = ...

    def create(self, validated_data):
        user = User(email=self.validated_data['email'])
        user.set_password(self.validated_data['password'])
        user.save()
        # create account
        account = Account(user=user)
        # create token for user
        token = Token.objects.update_or_create(user=user) 
        return user

您还需要根据自定义需求创建update方法。