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



所以,我有这个错误。我使用一个名为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

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)

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

@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)

但我建议在未来的项目中在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

最新更新