10

I have a model method that requires the request user to be pass in as an extra argument:

Model Method:

def has_achieved(self, user):
    return AwardLog.objects.filter(user=user, badge=self).count() > 0

Using the Django Rest Framework I want to call this put don't know how to pass in the extra argument from the Serializer:

class BadgeSerializer(serializers.ModelSerializer):

    achieved = serializers.SerializerMethodField(source='has_achieved(request.user???)')

    class Meta:
       model = Badge
       fields = ("name", "achieved")

I cannot find anywhere this scenario has been documented. is there a method in my views I could override to pass this in and use? Thanks.

Prometheus
  • 32,405
  • 54
  • 166
  • 302

1 Answers1

20

Just to follow-up I did this by using self.context['request'].user ie.

def has_achieved(self, obj):

    return obj.has_achieved(self.context['request'].user)
DannyMoshe
  • 6,023
  • 4
  • 31
  • 53
Prometheus
  • 32,405
  • 54
  • 166
  • 302