具有PhoneNumber类型的Djangophonefield对象的Djangographqljwt不可JSON序列化

2024-06-02 07:52:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我目前正在一个项目中使用django-phone-field库,在这个项目中我也使用graphene-django

这是我的自定义用户模型,我使用的是phone字段

class User(AbstractBaseUser, PermissionsMixin):
    """
    Custom User model to add the required phone number
    """
    first_name = models.CharField(
        max_length=100
    )
    last_name = models.CharField(
        max_length=100
    )
    email = models.EmailField(
        verbose_name='Email address',
        max_length=255,
        unique=True,
        # Because it's unique, blank is not an option because there could be 2 with the same value ('')
        blank=False,
        null=True
    )
    phone = CustomPhoneField(
        # Please note this formatting only works for US phone numbers right now
        # https://github.com/VeryApt/django-phone-field#usage
        # If international numbers are needed at some point, take a look at:
        # https://github.com/stefanfoulis/django-phonenumber-field
        E164_only=True,
        unique=True
    )
    is_active = models.BooleanField(default=True)
    is_admin = models.BooleanField(default=False)

    objects = UserManager()

    USERNAME_FIELD = 'phone'
    REQUIRED_FIELDS = ['first_name', 'last_name',]

我正在使用django-graphql-jwt来处理身份验证

这是我的tokenAuth查询:

mutation TokenAuth ($phone: String!, $password: String!) {
    tokenAuth(phone: $phone, password: $password) {
        token
        payload
        refreshExpiresIn
    }
}

服务器在尝试执行该查询时向我检索错误:

{
    "errors": [
        {
            "message": "Object of type PhoneNumber is not JSON serializable",
            "locations": [
                {
                    "line": 2,
                    "column": 5
                }
            ],
            "path": [
                "tokenAuth"
            ]
        }
    ],
    "data": {
        "tokenAuth": null
    }
}

我通过覆盖PhoneField的to_python方法临时制作了一个monkey补丁,如下所示:

class CustomPhoneField(PhoneField):
    """
    I had to override this to_python method because the phone field is now being used as the username field.
    In GraphQL JWT I was getting the following exception:
    Object of type PhoneNumber is not JSON serializable

    I don't really understand the implications of overriding this method.
    """
    def to_python(self, value):
        # Called during deserialization and from clean() methods in forms
        if not value:
            return None
        elif isinstance(value, PhoneNumber):
            return str(value)
        return str(value)

我想知道什么是这个问题的正确解决方案,也希望了解它到底是如何工作的,这样我就可以用一个更优雅的解决方案继续前进


Tags: thetodjangonametruefieldisvalue
1条回答
网友
1楼 · 发布于 2024-06-02 07:52:28

考虑到您的问题,我认为您正在尝试使用字符串而不是Json字段。如果电话号码是Json字段,您可以使用JsonString数据类型来尝试,这是可以克服的

相关问题 更多 >