Search code examples
djangodjango-rest-frameworkdjango-serializer

How to seralize a MethodField with more than one object in Django?


I want to serialize a method that checks if the author of a story is the currently logged in user, if so returns true, if not false. However, the Docs of Django state that the Serliazer method requires only one argument besides self. So how can I access the user model in addition to the story (object)?

I was thinking about something like that:

class StorySerializer(serializers.ModelSerializer):
    story_owner_permission = serializers.SerializerMethodField('check_story_owner_permission')

    class Meta:
        model = Story 
        fields =  ['story_owner_permission']

    def check_story_owner_permission(self, story, request):
        story_author = story.author.id
        current_user = request.user.id
        if (story_author == current_user):
            return True
        else:
            return False

But it doesn't work. check_story_owner_permission() missing 1 required positional argument: 'request'


Solution

  • You can use context in serializer, by default if you call your serializer from view, view have filled it automatically (see get_serializer_context):

    class StorySerializer(serializers.ModelSerializer):
        story_owner_permission = serializers.SerializerMethodField('check_story_owner_permission')
    
        class Meta:
            model = Story 
            fields =  ['story_owner_permission']
    
        def check_story_owner_permission(self, obj):
            return obj.author.id == self.context["request"].user.id