I'm using Django REST Framework to overide the get_serializer_context() method in my view class, below (view.py) so I can pass an extra context variable to my serializer below (serializer.py), but I'm receiving a null value when a view my API results in the browser. My results are below (result). Any help would be greatly appreciated.
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')
results
[
{
"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
}
]
You are getting your view context but no returning it with the update.
def get_serializer_context(self):
context = super(TaskListViewSet, self).get_serializer_context()
context.update({'request' : 'test'})
return context
I resolved the issue. I did not return the value from get_is_my_object(self, obj)
def get_first_name(self, obj):
test_me = self.context.get('request')
return test_me
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.