如何从View中将额外的上下文传递给Django Rest Serializer

时间:2016-10-30 21:45:55

标签: python django serialization

我正在使用Django REST Framework来覆盖我的视图类中的get_serializer_context()方法,在下面(view.py),所以我可以将一个额外的上下文变量传递给下面的序列化器(serializer.py),但我是在我的API生成浏览器的结果时收到空值。我的结果如下(结果)。任何帮助将不胜感激。

view.py

class TaskListMixin(object):
    s1 = Schedule.objects.get(pk=1)
    r1 = Room.objects.get(pk=2)
    sp1 = r1.spacetype.pk
    s = Space.objects.get(pk = sp1)
    queryset = s.task.all()
    serializer_class = SimpleSerializer3
    permission_classes = (permissions.IsAuthenticated,)


class TaskListViewSet(TaskListMixin, generics.BulkModelViewSet):

    def get_serializer_context(self):
        context = super(TaskListViewSet, self).get_serializer_context()
        return {'request' : 'test'}

serializer.py

class SimpleSerializer3(BulkSerializerMixin, ModelSerializer):


is_my_object = serializers.SerializerMethodField()

def get_is_my_object(self, obj):
    test_me = self.context.get('request')


class Meta(object):
    model = Task
    list_serializer_class = BulkListSerializer
    fields = ('pk','task_name', 'is_my_object')

结果

[
{
    "pk": 1,
    "task_name": "Remove large debris from floor",
    "is_my_object": null
},
{
    "pk": 2,
    "task_name": "Clean walls and horizontal surfaces",
    "is_my_object": null
},
{
    "pk": 3,
    "task_name": "Clean touch points",
    "is_my_object": null
},
{
    "pk": 4,
    "task_name": "Empty trash container",
    "is_my_object": null
},
{
    "pk": 6,
    "task_name": "Spot clean desks/furniture",
    "is_my_object": null
},
{
    "pk": 7,
    "task_name": "High/Low dust",
    "is_my_object": null
}
]

2 个答案:

答案 0 :(得分:0)

您正在获取视图上下文,但没有通过更新返回它。

   def get_serializer_context(self):
        context = super(TaskListViewSet, self).get_serializer_context()
        context.update({'request' : 'test'})
        return context

答案 1 :(得分:-1)

我解决了这个问题。我没有从get_is_my_object(self,obj)返回值

def get_first_name(self, obj):
    test_me = self.context.get('request')
    return test_me