[Django]-One to One relationship serializing in django

5👍

all you need is set source for profile:

class UserSerializer(serializers.ModelSerializer):
    password = serializers.CharField(write_only=True)
    location = LocationSerializer(read_only=True)
    profile = UserProfileSerializer(source='userprofile', read_only=True)

the userprofile is name of relation of your model User by onetoone to the UserProfle, other way you can set related_name for attribute user in the
UserProfle.

class UserProfile(models.Model):
    user = models.OneToOneField(User, related_name='profile', on_delete=models.CASCADE)

then your serializer will work fine as is.

Leave a comment