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!
You can write your own
to_representation
method.