Skip to content

Pydantic model field: convert empty string to None #2687

Discussion options

You must be logged in to vote

Hi @natasha-aleksandrova
You can achieve what you want by either create a custom type

from typing import Optional, Union

from pydantic import BaseModel
from pydantic.validators import str_validator


def empty_to_none(v: str) -> Optional[str]:
    if v == '':
        return None
    return v


class EmptyStrToNone(str):
    @classmethod
    def __get_validators__(cls):
        yield str_validator
        yield empty_to_none


class M(BaseModel):
    x: Union[None, int, EmptyStrToNone]


assert M(x=None).x is None
assert M(x=0).x == 0
assert M(x='').x is None
assert M(x='q').x == 'q'

or add a validator

from typing import Union

from pydantic import BaseModel as PydanticBaseModel, validator

Replies: 3 comments 11 replies

Comment options

You must be logged in to vote
8 replies
@wiryonolau
Comment options

@VanDuongEmpire
Comment options

@wiryonolau
Comment options

@VanDuongEmpire
Comment options

@frederickch
Comment options

Answer selected by natasha-aleksandrova
Comment options

You must be logged in to vote
3 replies
@y2kbugger
Comment options

@conradogarciaberrotaran
Comment options

@y2kbugger
Comment options

Comment options

You must be logged in to vote
0 replies
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
10 participants