To get the value of the ChoiceField in Django Rest Framework (DRF), you can use the following steps:

  1. Define your ChoiceField in your serializer. For example:
from rest_framework import serializers

class MySerializer(serializers.Serializer):
    OPTIONS = (
        ('option1', 'Option 1'),
        ('option2', 'Option 2'),
        ('option3', 'Option 3'),
    )
    my_choice_field = serializers.ChoiceField(choices=OPTIONS)
  1. In your view, you can access the value of the ChoiceField by calling the serializer's data attribute:
from rest_framework.views import APIView
from rest_framework.response import Response

class MyView(APIView):
    serializer_class = MySerializer

    def post(self, request):
        serializer = self.serializer_class(data=request.data)
        if serializer.is_valid():
            my_choice_field_value = serializer.data['my_choice_field']
            # do something with my_choice_field_value
            return Response({'success': True})
        else:
            return Response(serializer.errors, status=400)

In the post method above, serializer.data returns a dictionary of validated data, including the value of the my_choice_field field. You can access this value using the key 'my_choice_field'.

django choicefiled value get drf

原文地址: https://www.cveoy.top/t/topic/bsLp 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录