Serializer Extend User field by same level with Ma

2019-08-10 22:50发布

I write a Extend User serializers in Django like this:

File Models.py Extend User App:

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')

File serializers.py Extend User App:

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',
        ]

This serializer in order to extend for Main User Serializers:

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

As a result, my API will render into this:

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

But now I want to API in same level with main User like this:

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

Please help me to do this. Thanks in advance!

1条回答
淡お忘
2楼-- · 2019-08-10 23:19

You can write your own to_representation method.

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
查看更多
登录 后发表回答