I created a user profile using Django auth user so I want to get username, email and phone using UserProfile model serializer, so it is possible to get data from from a foreign-key relation using ModelSerializer in Django rest framework. I am not getting any useful solution from documentation and Google, please help.
class UserProfile(models.Model):
user = models.ForeignKey(User,)
phone = models.CharField(max_length=15, blank=True)
class UserProfileSerializer(serializers.ModelSerializer):
class Meta:
model=UserProfile
fields = (phone,'user__username','user__email')
You need to define the username
and email
fields in your serializer and pass the source
argument with dotted notation to traverse attributes in the User
model.
You need to do something like:
class UserProfileSerializer(serializers.ModelSerializer):
username = serializers.CharField(source='user.username', read_only=True)
email = serializers.EmailField(source='user.email', read_only=True)
class Meta:
model=UserProfile
fields = (phone, username, email)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With