vitalik / django-ninja

💨 Fast, Async-ready, Openapi, type hints based framework for building APIs
https://django-ninja.dev
MIT License
7.27k stars 432 forks source link

Django EmailField in ModelSchema #358

Open bertraol opened 2 years ago

bertraol commented 2 years ago

Hey, first of all I'd like to say how much I appreciate this project and all the effort that is being invested here. Nice work!

I noticed that in order to get ModelSchema to validate an EmailField as an email and not as a string, i need to define the ModelSchema like this:

from pydantic import EmailStr

class MyUserSchema(ModelSchema):
    email: EmailStr
    class Config:
        model = MyUserModel
        model_fields = [
            "id",
            "first_name",
            "last_name,
        ]

It would be nice if EmailStr would be the default type for Django EmailField out of the box. Or is there any reason why this would be a bad idea?

I tried fiddling a bit with orm/fields.py without luck. If I can get some hints if and how I could approach this issue, I'd love to try to contribute.

Maybe it's enough to make it explicit in the documentation how it currently works?

bertraol commented 2 years ago

Okay, i got a PoC working by handling this case in get_schema_field() in orm/fields.py

if field.verbose_name.title() == "Emailfield":
    max_length = None
    python_type = EmailStr

This requires python-email-validator to be installed.

It's not a very elegant solution, I must admit

vitalik commented 2 years ago

Hi @bertraol

yeah, the main reason is the python-email-validator dependency... while django has it's own

I guess I'll push some custom EmailStr pydantic field that will use django email validation instead of dependency