Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Default Resolver for custom field types #678

Open
Jragon opened this issue Feb 10, 2023 · 4 comments
Open

Default Resolver for custom field types #678

Jragon opened this issue Feb 10, 2023 · 4 comments

Comments

@Jragon
Copy link
Contributor

Jragon commented Feb 10, 2023

Hi there,

I'm want to resolve the django PhoneNumberField into a string by default. At the moment I would have to write a resolve_phone func on each schema just to call str(obj.phone). Is it possible to write a default resolve for a specific field type from the ORM?

I guess that CharField must output an str or IntegerField will output an int - how can I make PhoneNumerField output a str? Are these changes on the field type itself?

Cheers

@OtherBarry
Copy link
Contributor

You could potentially extend ninja.orm.field.TYPES

@Jragon
Copy link
Contributor Author

Jragon commented Feb 10, 2023

As far as I understand this is for creating schemas directly from models. I got a bit confused trying to figure out how the from_orm method actually resolves a CharField to a str.

my schema looks like:

class OutSchema(Schema):
    phone: str
    # ...

And my model looks like:

class ModelWithPhone(models.Model):
    phone = PhoneNumberField(...)
    # ...

In order to get my schema to work properly I have to add a custom resolver everywhere I want a phone number:

class OutSchema(Schema):
    phone: str
    # ...

    @staticmethod
    def resolve_phone(obj):
        return str(obj.phone)

@chrismaille
Copy link

Can you can try this?

class PhoneNumberOut(str):
    @classmethod
    def __get_validators__(cls):
        yield cls.validate

    @classmethod
    def validate(cls, v):
        return cls(v)

    def __repr__(self):
        return f"PhoneNumberField({super().__repr__()})"
class OutSchema(Schema):
    phone: PhoneNumberOut

https://docs.pydantic.dev/usage/types/#generic-classes-as-types

@Jragon
Copy link
Contributor Author

Jragon commented Feb 20, 2023

Ooo sweet, perfect. Thanks Chris :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants