Django-rest login response with more data

Viewed 146

I have a User and Post models with many-to-many relation. Now in my App after successful log in I'm sending request to api to fetch user's posts. I'm not sure if it's the best idea to send 2 seperate requests. Is there any way to provide user posts in successful login request along with user, access/refresh token?

1 Answers

If you're using django-rest-auth, you can do this by simply overriding REST_AUTH_SERIALIZERS:

REST_AUTH_SERIALIZERS = {
    'LOGIN_SERIALIZER': 'path.to.custom.LoginSerializer',
    'TOKEN_SERIALIZER': 'path.to.custom.TokenSerializer',
    ...
}

Then create your custom serializer, for example:

# serializers.py
class CustomTokenSerializer(serializers.ModelSerializer):
    posts= serializers.SerializerMethodField()

    def get_posts(self, instance):
        return PostSerializer(instance.user.posts.all(), many=True).data

    class Meta:
        model = Token
        fields = ('key', 'posts')

# base.py
REST_AUTH_SERIALIZERS = {
    'TOKEN_SERIALIZER': 'accounts.serializer.CustomTokenSerializer'
}

See the official documentation here.

Related