PhoneNumber 类型的 Django REST Framework 对象不可 JSON 序列化

Hen*_*rik 3 django django-rest-framework

所以,我有这个错误。我使用名为 的第三方包PhoneNumber。现在,当我想序列化我的数据时,我收到此错误:Object of type PhoneNumber is not JSON serializable

我可以猜测问题是什么,但不知道如何解决它:/以前有人遇到过这个/类似的问题吗?:)

serializer.py

from rest_framework import serializers
from phonenumber_field.serializerfields import PhoneNumberField

from user.models import Account



class RegistrationSerializer(serializers.ModelSerializer):

    password2 = serializers.CharField(style={'input_type': 'password'}, write_only=True)
    # country = serializers.ChoiceField(
    #   choices=['US', 'DE', 'FR', 'CH', 'AT', 'GB', 'SE', 'NO', 'FI', 'DK', 'IT', 'ES', 'PT']
    # )
    phone_number = PhoneNumberField()


    class Meta:
        model = Account
        fields = ['phone_number', 'username', 'first_name', 'country', 'email', 'password', 'password2']


        
        extra_kwargs = {
                'password': {'write_only': True},
        }   


    def save(self):

        account = Account(
                    email = self.validated_data['email'],
                    username = self.validated_data['username'],
                    first_name = self.validated_data['first_name'],
                    country = self.validated_data['country'],
                    phone_number = self.validated_data['phone_number'],
                )
        password = self.validated_data['password']
        password2 = self.validated_data['password2']
        if password != password2:
            raise serializers.ValidationError({'password': 'Passwords must match.'})
        account.set_password(password)
        account.save()
        return account
Run Code Online (Sandbox Code Playgroud)

views.py

from rest_framework import status
from rest_framework.response import Response
from rest_framework.decorators import api_view

from .serializers import RegistrationSerializer


@api_view(['POST', ])
def registration_view(request):

    if request.method == 'POST':
        serializer = RegistrationSerializer(data=request.data)
        data = {}
        if serializer.is_valid():
            account = serializer.save()
            data['response'] = 'successfully registered new user.'
            data['email'] = account.email
            data['first_name'] = account.first_name
            data['phone_number'] = account.phone_number
            data['email'] = account.email
            data['username'] = account.username
            data['country'] = account.country
        else:
            data = serializer.errors
        return Response(data)
Run Code Online (Sandbox Code Playgroud)

小智 6

尝试这个。这是最简单的解决方案。

@api_view(['POST', ])
def registration_view(request):

    if request.method == 'POST':
        serializer = RegistrationSerializer(data=request.data)
        data = {}
        if serializer.is_valid():
            ...
            data['phone_number'] = str(account.phone_number)
            ...
        return Response(data)
Run Code Online (Sandbox Code Playgroud)

但我建议在未来的项目中这样做serializers.py

class RegistrationSerializer(serializers.ModelSerializer):
    ...
    def to_representation(self, instance):
        data = super().to_representation(instance)
        data['response'] = 'successfully registered new user.'
        data['email'] = instance.email
        data['first_name'] = instance.first_name
        data['phone_number'] = str(instance.phone_number)
        data['email'] = instance.email
        data['username'] = instance.username
        data['country'] = instance.country
        return data
Run Code Online (Sandbox Code Playgroud)