stefanfoulis / django-phonenumber-field

A django model and form field for normalised phone numbers using python-phonenumbers
MIT License
1.48k stars 318 forks source link

Usage with django ninja #572

Closed kimdre closed 9 months ago

kimdre commented 1 year ago

When I try to get data with phone numbers with the Python Ninja API, I get an error that a string was expected, but not returned:

response -> phone_number
  str type expected (type=type_error.str)

I tried to change the annotation as explained in the Ninja docs but dind't succeed. What do I have to import and use as an type annotation for this to work?

kimdre commented 1 year ago

Ok I was able to fix this issue with this code

from phonenumber_field.phonenumber import PhoneNumber  # added this

class UserSchema(ModelSchema):
    phone_number: PhoneNumber  # added this
    class Config:
        model = User
        model_exclude = ['password', 'user_permissions', 'groups']
        arbitrary_types_allowed = True  # added this

But now I have another problem.

ValueError: Value not declarable with JSON Schema, field: name='phone_number' type=PhoneNumber required=True
francoisfreitag commented 1 year ago

At some point, I think you’ll need to call str(user.phone_number). That way, Django ninja will deal with an str instead of a PhoneNumber object.

nullandvoid-digital commented 12 months ago

@francoisfreitag whereabouts in the project would this be called? I'm even using Pydantic's own phonenumber wrapper and I'm still having the same problem as OP

francoisfreitag commented 12 months ago

I don’t know. I’ve never used django ninja and only slightly Pydantic. But when you’re serializing to an interoperable type (e.g. JSON), where there is no standard type for phone number, you’ll need to find a supported type that can convey the information. String seems to be the most appropriate type in JSON. Phone numbers are usually represented as string. That’s why I advised to call str(user.phone_number) at some point earlier.

francoisfreitag commented 9 months ago

Closing for inactivity.