[Fixed]-Add user specific fields to Django REST Framework serializer

27๐Ÿ‘

you can do it with SerializerMethodField

Example :

class PostSerializer(serializers.ModelSerializer):
    fav = serializers.SerializerMethodField('likedByUser')

    def likedByUser(self, obj):
        request = self.context.get('request', None)
        if request is not None:
            try:
                liked=Favorite.objects.filter(user=request.user, post=obj.id).count()
                return liked == 1
            except Favorite.DoesNotExist:
                return False
        return "error"

    class Meta:
        model = Post

then you should call serializer from view like this:

class PostView(APIVIEW):
     def get(self,request):
         serializers = PostSerializer(PostObjects,context={'request':request})
๐Ÿ‘คrapid2share

8๐Ÿ‘

Iโ€™d be inclined to try and put as much of this as possible on the Like model object and then bung the rest in a custom serializer field.

In serializer fields you can access the request via the context parameter that they inherit from their parent serializer.

So you might do something like this:

class LikedByUserField(Field):
    def to_native(self, article):
        request = self.context.get('request', None)
        return Like.user_likes_article(request.user, article)

The user_likes_article class method could then encapsulate your prefetching (and caching) logic.

I hope that helps.

๐Ÿ‘คCarlton Gibson

1๐Ÿ‘

According to the Django Documentation โ€“ SerializerMethodField, I had to change the code of rapid2share slightly.

class ResourceSerializer(serializers.ModelSerializer):
    liked_by_user = serializers.SerializerMethodField()

    def get_liked_by_user(self, obj : Resource):
        request = self.context.get('request')
        return request is not None and obj.likes.filter(user=request.user).exists()
๐Ÿ‘คTobias Ernst

Leave a comment