【问题标题】:Django REST Framework Object of type PhoneNumber is not JSON serializablePhoneNumber 类型的 Django REST 框架对象不是 JSON 可序列化的
【发布时间】:2021-06-18 13:57:59
【问题描述】:

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

【问题讨论】:

    标签: django django-rest-framework


    【解决方案1】:

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

    @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
    

    【讨论】:

    • 谢谢!有时最简单的解决方案是最好的! :)
    猜你喜欢
    • 2020-07-05
    • 2021-12-03
    • 2019-09-28
    • 2021-06-22
    • 1970-01-01
    • 2022-07-01
    • 2023-01-10
    • 2019-04-29
    • 2017-08-13
    相关资源
    最近更新 更多