Django How to Serialize from ManyToManyField and List All
I think what you need is the nested serializer:
class FollowerSerializer(serializers.ModelSerializer):
username = serializers.CharField(source='user__username')
class Meta:
model = UserProfile
fields = ('username', )
class FollowerSerializer(serializers.ModelSerializer):
followers = FollowerSerializer(many=True, read_only=True)
class Meta:
model = UserProfile
fields = ('followers', )
I used nested relationships in this link. Django Rest Framework Nested Relationships
Added a new serializer for only username of the user and also changed the other serializer.
# serializes only usernames of users
class EachUserSerializer(serializers.ModelSerializer):
username = serializers.CharField(source='user.username')
class Meta:
model = UserProfile
fields = ('username',)
class FollowerSerializer(serializers.ModelSerializer):
followers = EachUserSerializer(many=True, read_only= True)
followings = EachUserSerializer(many=True,read_only=True)
class Meta:
model = UserProfile
fields = ('followers','followings')
Output was just what was I looking for:
{
"followers": [],
"followings": [
{
"username": "sneijder"
},
{
"username": "drogba"
}
]
}
Thank you for your help anyway :)