[Django]-Return one-to-one model information with model in Django

4๐Ÿ‘

โœ…

Well, what prefetch_related does is load the data from UserProfile model beforehand based on relationship between User model and UserProfile model, so when you call user.userprofile it does not hit database again. But it does not return the value when you call user. So in your model serializer, you can add these two fields with source pointing to UserProfileโ€˜s first_name and last_name. For example:

class UserSerializer(serializer.ModelSerializer):
     first_name = serializer.CharField(source='userprofile.first_name', read_only=True)
     last_name = serializer.CharField(source='userprofile.last_name', read_only=True)

     class Meta:
         model = User
         fields = ['email', 'first_name', 'last_name']
๐Ÿ‘คruddra

0๐Ÿ‘

You could define two serializers:

class UserProfileSerializer(serializer.ModelSerializer):
    class Meta:
        model = UserProfile
        fields = ['first_name', 'last_name']
class UserSerializer(serializer.ModelSerializer):
    user_profile = UserProfileSerializer(many=False)

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

    class Meta:
        model = User
        fields = ['email']

Hope it helps you ๐Ÿ™‚

๐Ÿ‘คAlejandroid

Leave a comment