Harshit Chauhan
Harshit Chauhan

Reputation: 155

django rest framework get data from foreign key relation

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

Upvotes: 8

Views: 2695

Answers (3)

Rahul Gupta
Rahul Gupta

Reputation: 47896

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)

Upvotes: 14

Gocht
Gocht

Reputation: 10256

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

Upvotes: 2

Jayaram
Jayaram

Reputation: 6606

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

Upvotes: 2

Related Questions