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.
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.
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.
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With