singerng singerng - 8 months ago 79
Python Question

Django REST Custom View Parameters in Viewset with CoreAPI

If I define a django-rest-framework view framework as:

class ProblemViewSet(viewsets.ModelViewSet):
queryset = Problem.objects.all()
serializer_class = ProblemSerializer

@detail_route(methods=['post'], permission_classes=(permissions.IsAuthenticated,))
def submit(self, request, *args, **kwargs):
# my code here
return Response(...)

When I look at the CoreAPI schema that is defined, I find this:

problems: {
create(title, text, value, category, hint)
partial_update(pk, [title], [text], [value], [category], [hint])
update(pk, title, text, value, category, hint)

I'd like the
API endpoint to take an additional parameter, called
, but so far I haven't figured out how to add such a custom parameter. I know I can just pass in the POST array, but that seems inelegant and un-RESTful. Any ideas?


I don't understand your question, but I think that you want to add in the input the filed answer to django-rest form or raw, you can do this adding in the serializer ProblemSerializer the next:

from rest_framework import serializers
class CustomerSerializer(serializers.ModelSerializer):
    answer = serializers.SerializerMethodField()
    class Meta:
        model = Problem
        fields = ['answer', 'my-normal-params',...]

def get_answer(self, problem):
    if hasattr(problem, 'answer'):
        request = self.context['request']
        return answer

In get_answer method you will display in the json the value that you want, or you can return None (null) if you want,

If that is not your problem, please say me, I'll help you.