user13926973
user13926973

Reputation:

How should I return usernames instead of id inside Django Rest Framework API?

This is my model.

class FollowerModelSerializer(ModelSerializer):
    user = CharField(source='slug')

    class Meta:
        model = Profile
        fields = ['user', 'followers']

This is the serializer.

class FollowerModelViewSet(ModelViewSet):
    queryset = Profile.objects.all()
    serializer_class = FollowerModelSerializer
    allowed_methods = ('GET', 'HEAD', 'OPTIONS')

    def list(self, request, *args, **kwargs):
        self.queryset = self.queryset.filter(id=request.user.id)
        return super(FollowerModelViewSet, self).list(request, *args, **kwargs)

And this is the API.

This is the response :

HTTP 200 OK
Allow: GET, HEAD, OPTIONS
Content-Type: application/json
Vary: Accept

[
    {
        "user": "pop",
        "followers": [
            1,
            4
        ]
    }
]

Problem: It's returning the IDs of the followers. How should I make it return the usernames of the followers instead?

Upvotes: 0

Views: 482

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 477704

You can work with a SlugRelatedField [drf-doc]:

class FollowerModelSerializer(ModelSerializer):
    user = CharField(source='slug')
    followers = SlugRelatedField(
        slug_field='username',
        many=True,
        read_only=True
    )

    class Meta:
        model = Profile
        fields = ['user', 'followers']

This will thus use the username of the objects contained in the followers relation.

Upvotes: 1

Related Questions