Django How to Serialize from ManyToManyField and List All

前端 未结 2 1188
梦谈多话
梦谈多话 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', )
    
    0 讨论(0)
  • 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 :)

    0 讨论(0)
提交回复
热议问题