Django How to Serialize from ManyToManyField and List All

前端 未结 2 1298
梦谈多话
梦谈多话 2021-02-09 13:51

I\'m developing a mobile application backend with Django 1.9.1 I implemented the follower model and now I want to list all of the followers of a user but I\'m currently stuck t

2条回答
  •  轮回少年
    2021-02-09 14:26

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

提交回复
热议问题