django - Wrapping fields into additional JSON object -
what way alter construction of json returned django rest framework's default model serialiers?
example -
restaurant object returned drf right now:
{ "id":9, "label":"pizza hut" "like_id:":32, "like_quantity":2 }
more desirable json structure:
{ "id":9, "label":"pizza hut", "social": { "like_id:":32, "like_quantity":2 } }
to create json structure, want few fields default json nested under new field.
if right, want this:
{ "id":9, "label":"pizza hut", "social": { "like_id:":32, "like_quantity":2 } }
to result of request.
you can edit homecoming values within generic view, if using one, eg:
class restaurantviewset(mixins.retrievemodelmixin, viewsets.genericviewset): queryset = restaurant.objects.all() serializer_class = restaurantserializer def retrieve(self, request, pk=none): queryset = restaurant.objects.all() restaurant = get_object_or_404(queryset, pk=pk) serializer = restaurantserializer(user,context={'request': request}) results = { "id":serializer.data['id'], "label":serializer.data['label'], "social": { "like_id:":serializer.data['like_id'], "like_quantity":serializer.data['like_quantity'] } } homecoming response(results)
django django-rest-framework
No comments:
Post a Comment