我使用Django REST Framework有以下序列化器。

这是我到目前为止所拥有的...

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'),

此代码段存在一些问题。

1)pram pk = 19是硬编码的,应该是我尝试过的self.kwargs['profile_id'].,但是我不知道如何将kwarg传递给该方法,并且无法使profile_id正常工作。也就是说,我无法从网址中获取它。

2)该代码中是否应包含任何代码?我尝试添加到模型中,但是可以再次通过args。

models.py
即方法类
     def get_score(self, profile):

        score = [val for val in self.attribute_answers.all() if val in
profile.attribute_answers.all()]
            return len(score)

最佳答案

序列化器传递给上下文字典,该字典包含 View 实例,因此您可以通过执行以下操作来获取profile_id:

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

但是在这种情况下,我认为您不需要这样做,因为无论如何都将'obj'设置为配置文件实例。

是的,您可以将“get_this_score”方法放在模型类上。您仍然需要'SerializerMethodField',但它只需调用'return obj.get_this_score(...)',即可从序列化程序上下文中设置任何参数。

请注意,序列化程序上下文还将包含“request”,因此,如果需要,您还可以访问“request.user”。

关于django - Rest Framework序列化器方法,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/14921552/

10-11 05:16
查看更多