Как использовать поле сериализатора и сделать ответ из данных поля выбора в django rest framework
Как использовать поле сериализатора в DRF
models.py
class User(models.Model):
id = models.AutoField(primary_key=True)
first_name = models.CharField(max_length=255, null=True, unique=True)
birthdate = models.DateField(null=True, blank=False)
gender_choice = [
('male','male'),
('female','female')
]
gender = models.CharField(max_length=255, choices=gender_choice, default='male', null=True)
остальные ответы ниже
serializers.py
class UserRegSerializer(serializers.ModelSerializer):
show_me = serializers.SerializerMethodField('get_show_me') #the extra serializer field
class Meta:
model = User
fields = ('id', 'first_name', 'birthdate', 'gender')
def get_show_me(self, showmeobj): #this fuction returns the data
gender = getattr(showmeobj, 'gender')
if gender == 'male':
return 'Queen' #if user's gender is male (opposite gender)
else:
return 'King' #if user's gender is female (opposite gender)
view.py
class UserCreateAPIView(generics.CreateAPIView):
serializer_class = UserRegSerializer
queryset = User.objects.all()
def post(self, request):
first_name = request.data.get('first_name', False)
birthdate = request.data.get('birthdate', False)
gender = request.data.get('gender', False)
serializer = UserRegSerializer(data=request.data)
if serializer.is_valid():
serializer.save()
return Response({
'status': True,
'message': 'Register User Successfully',
'data': serializer.data,
}, status = status.HTTP_201_CREATED)
else :
return Response({
'status': False,
'message': 'Error! something went wrong',
}, status = status.HTTP_400_BAD_REQUEST)
надеюсь, этот ответ поможет вам. изменения приняты:)