串行器将用户字段与Django Rest Framework中的主用户扩展相同级别

时间:2018-01-11 10:39:46

标签: django django-rest-framework

我在Django中编写了一个Extend User序列化程序,如下所示:

文件 Models.py 扩展用户应用

class Profile(models.Model):
    user = models.OneToOneField(User, unique=True)
    nickname = models.CharField(max_length=50, null=True, blank=True)
    gender = models.CharField(max_length=100, choices=GENDER_CHOICES, blank=True, null=True, default='MALE')

文件 serializers.py 扩展用户应用

class ProfilePatchSerializer(ModelSerializer):
    languages = serializers.ChoiceField(choices=LANGUAGE_CHOICES, default='EN')
    gender = serializers.ChoiceField(choices=GENDER_CHOICES, default='1')
    class Meta:
        model = Profile
        fields = [
            'gender',
            'language',
        ]

此序列化程序为了扩展主用户序列化程序:

class UserCreateUpdateSerializer(ModelSerializer):
    profile = ProfilePatchSerializer()
    class Meta:
        model = User
        fields = [
            'username',
            'email',
            'first_name',
            'last_name',
            'profile',
        ]

因此,我的API将呈现为:

{
    "id": 1,
    "username": "feedgit",
    "first_name": "Feed Git",
    "profile": {
        "gender": Male,
        "languages": English
    }
}

但是现在我想要与主用户处于相同级别的API,如下所示:

{
   "id": 1,
   "username": "feedgit",
   "first_name": "Feed Git",
   "gender": Male,
   "languages": English
}

请帮我这样做。提前谢谢!

1 个答案:

答案 0 :(得分:3)

您可以编写自己的to_representation方法。

class UserCreateUpdateSerializer(ModelSerializer):
    profile = ProfilePatchSerializer()
    class Meta:
        model = User
        fields = [
            'username',
            'email',
            'first_name',
            'last_name',
            'profile',
        ]

    def to_representation(self, instance):
        data = super(UserCreateUpdateSerializer, self).to_representation(instance)
        profile = data.pop('profile')
        for key, val in profile.items():
            data.update({key: val})
        return data