Django rest framework get data from foreign key relationship

I created a user profile using the Django auth user, so I want to get the username, email address and phone using the UserProfile model serializer, so I can get data from the foreign key relationship using the ModelSerializer in the Django rest framework. I am not getting any useful solution from the 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') 
+5
source share
3 answers

You need to define the username and email fields in your serializer and pass the source argument with dotted notation to move the 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) 
+8
source

If you are using rest - I would suggest offering a serialization of a user model something like this

 class UserSerializer(serializers.ModelSerializer): phone = serializers.PrimaryKeyRelatedField(many=True, read_only=True) class Meta: model = User fields = ('username', 'email', 'phone') 

If you want to achieve the opposite:

 class UserProfileserializer(serializers.ModelSerializer): username = serializers.RelatedField(source='user', read_only=True) email = serializers.RelatedField(source='user', read_only=True) class Meta: model = UserProfile fields = ('username','email','phone') 
+2
source

Try the following:

 # import your serializer class from myapp.serializers import UserProfileSerializer class UserSerializer(serializers.ModelSerializer): phone = UserProfileSerializer(many=True, read_only=True) class Meta: model = User fields = ('username', 'email', 'phone') 
+2
source

All Articles