Django How to Serialize from ManyToManyField and List All

前端 未结 2 1191
梦谈多话
梦谈多话 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:37

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

提交回复
热议问题