7
votes

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')
3

3 Answers

13
votes

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)
2
votes

If you're using rest - i would suggest suggest serializing the 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 reverse as well:

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
votes

Try this:

# 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')