Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django Rest Framework SerializerMethodField Pass Extra Argument

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.

like image 686
Prometheus Avatar asked Jul 17 '14 15:07

Prometheus


People also ask

How do I pass extra data to a serializer?

In function-based views, we can pass extra context to serializer with “context” parameter with a dictionary. To access the extra context data inside the serializer we can simply access it with “self. context”. From example, to get “exclude_email_list” we just used code 'exclude_email_list = self.

What is the difference between ModelSerializer and HyperlinkedModelSerializer?

The HyperlinkedModelSerializer class is similar to the ModelSerializer class except that it uses hyperlinks to represent relationships, rather than primary keys. By default the serializer will include a url field instead of a primary key field.

What is the purpose of serialization in Django REST Framework?

Serializers in Django REST Framework are responsible for converting objects into data types understandable by javascript and front-end frameworks. Serializers also provide deserialization, allowing parsed data to be converted back into complex types, after first validating the incoming data.


1 Answers

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)
like image 63
Prometheus Avatar answered Sep 28 '22 07:09

Prometheus