Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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')
like image 638
Harshit Chauhan Avatar asked Sep 10 '15 19:09

Harshit Chauhan


1 Answers

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)
like image 163
Rahul Gupta Avatar answered Oct 20 '22 03:10

Rahul Gupta