Serializer Method for Open Framework

I have the following Serializer using the Django REST Framework .

This is what I still have ...

serializer.py

class ProductSerializer(serializers.ModelSerializer): score = serializers.SerializerMethodField('get_this_score') class Meta: model = Product fields = ('id', 'title', 'active', 'score') def get_this_score(self, obj): profile = Profile.objects.get(pk=19) score = [val for val in obj.attribute_answers.all() if val in profile.attribute_answers.all()] return (len(score)) 

urls.py

  url(r'^products/(?P<profile_id>.+)/$', ProductListScore.as_view(), name='product-list-score'), 

There are several problems with this piece of code.

1) The stroller pk = 19 is hard-coded, it must be self.kwargs['profile_id']. I tried and tried, but I do not know how to pass kwarg to a method and cannot make profile_id work. that is, I cannot get it from the url.

2) If any of this code is in models? I tried adding to the models, but again I can pass the arguments.

models.py i.e. method class

  def get_score(self, profile): score = [val for val in self.attribute_answers.all() if val in profile.attribute_answers.all()] return len(score) 
+8
django django-models django-rest-framework
source share
2 answers

Serializers are passed in by a context dictionary that contains an instance of the view, so you can get profile_id by doing something like this:

 view = self.context['view'] profile_id = int(view.kwargs['profile_id']) 

However, in this case, I do not think you need to do this, since in any case, "obj" will be installed in the profile instance.

And yes, you could put the get_this_score method in a model class. You'll still need SerializerMethodField, but it just calls return obj.get_this_score (...), setting any arguments from the serializer context.

Note that in the context of the serializer, "request" will also be included, so you can also access "request.user" if necessary.

+21
source share

To answer Jasonโ€™s answer question to Tomโ€™s answer, you can access the request object through the same contextual mechanism as this. You reference query objects from the ModelMethod definition; you do not pass them. I was able to use this to access the current request.user object, as shown below:

 class ProductSerializer(serializers.ModelSerializer): score = serializers.SerializerMethodField('get_this_score') class Meta: model = Product fields = ('id', 'title', 'active', 'score') def get_this_score(self, obj): profile = self.context['request'].user score = [val for val in obj.attribute_answers.all() if val in profile.attribute_answers.all()] return (len(score)) 
+7
source share

All Articles