Created
November 7, 2023 15:33
-
-
Save wapiflapi/1675135f2c21845cffcd957200214abc to your computer and use it in GitHub Desktop.
A test showing how to handle empty string == null in different scenarios.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import typing | |
import pydantic | |
class TestBaseModel(pydantic.BaseModel): | |
@pydantic.validator('*', pre=True) | |
def empty_str_to_none(cls, v): | |
if v == "": | |
return None | |
return v | |
class TestModel(TestBaseModel): | |
str_or_none: typing.Optional[str] | |
int_or_none: typing.Optional[int] | |
int_or_none_json: typing.Optional[pydantic.Json[int]] | |
int_list_or_none: typing.Optional[typing.List[int]] | |
int_list: typing.List[int] | |
@pydantic.validator("int_list", pre=True) | |
def null_or_empty_str_results_in_empty_list(cls, v): | |
return v if v else [] | |
int_list_or_none_json: typing.Optional[pydantic.Json[typing.List[int]]] | |
int_list_json: pydantic.Json[typing.List[int]] | |
@pydantic.validator("int_list_json", pre=True) | |
def null_or_empty_str_results_in_empty_json_list(cls, v): | |
return v if v else "[]" | |
# Keep in mind you can do: | |
a: int = 1 | |
b: int = 2 | |
c: int = 3 | |
@pydantic.validator("a", "b", "c", pre=True) | |
def this_applies_to_multiple_fields(cls, v): | |
return v | |
def test_demo_model(): | |
test_model = TestModel.parse_obj(dict( | |
str_or_none="something", | |
int_or_none=123, | |
int_or_none_json="123", | |
int_list_or_none=[1, 2, 3], | |
int_list=[1, 2, 3], | |
int_list_or_none_json="[1, 2, 3]", | |
int_list_json="[1, 2, 3]", | |
)) | |
assert test_model.str_or_none == "something" | |
assert test_model.int_or_none == 123 | |
assert test_model.int_or_none_json == 123 | |
assert test_model.int_list_or_none_json == [1, 2, 3] | |
assert test_model.int_list_json == [1, 2, 3] | |
test_model = TestModel.parse_obj(dict( | |
str_or_none="", | |
int_or_none="", | |
int_or_none_json="", | |
int_list_or_none="", | |
int_list="", | |
int_list_or_none_json="", | |
int_list_json="", | |
)) | |
assert test_model.str_or_none is None | |
assert test_model.int_or_none is None | |
assert test_model.int_or_none_json is None | |
assert test_model.int_list_or_none is None | |
assert test_model.int_list == [] | |
assert test_model.int_list_or_none_json is None | |
assert test_model.int_list_json == [] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment