Django Ошибка сериализатора ожидаемое число, но получил [28] - PullRequest
0 голосов
/ 03 мая 2020

Я новичок в Django и Python, я использую Django -rest-framework для построения RESTfull API. У меня есть такое представление

class ProfileViewSet(APIView):

# to find if isAuthenticate then
authentication_classes = (TokenAuthentication,)
permission_classes = [permissions.IsAuthenticated]

 def post(self, request):
    user_id = request.data['user_id']
    request.data.pop('user_id')
    request.data['user_id'] = int(user_id)
    serializer = ProfileSerializer(
        context={'request': request}, data=request.data)

    if serializer.is_valid():
        serializer.create(validated_data=request.data)
        return Response(serializer.data)
    return Response(serializer.errors)

, и мой сериализатор отправляет что-то вроде этого

class ProfileSerializer(serializers.ModelSerializer):
    # id = serializers.IntegerField(source='profile.id')
    user_id = serializers.IntegerField(source='user.id')
    user = serializers.PrimaryKeyRelatedField(
        read_only=True, default=serializers.CurrentUserDefault())
    profile = Profile
    # depth=2

    class Meta:
        model = Profile
        fields = ('id', 'user', 'image', 'first_name', 'last_name',
                  'description', 'mobile', 'current_location', 'user_id')
        read_only_fields = ('user', 'user_id')

из моего внешнего интерфейса, я отправляю user_id в виде строки, поэтому я анализирую ее номер.

ошибка: - TypeError: Field 'id' expected a number but got [28].

JSON из request.data:- 'user_id':'28' 'first_name':'sdsd' 'last_name':'dsd' 'mobile':'2323323' 'current_location':'23233' description':'23'

1 Ответ

0 голосов
/ 04 мая 2020

в JSON, «28» отличается от 28, как и язык программирования, потому что «28» - это строка, а не число

...