From dce53bc04b9e0d47683fe73f66ce1f1cde04cb6d Mon Sep 17 00:00:00 2001 From: Mevaser Date: Sun, 19 Mar 2023 23:38:37 +0200 Subject: [PATCH] Optional relationships fields --- tortoise/contrib/pydantic/creator.py | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/tortoise/contrib/pydantic/creator.py b/tortoise/contrib/pydantic/creator.py index ff1453b19..d99509909 100644 --- a/tortoise/contrib/pydantic/creator.py +++ b/tortoise/contrib/pydantic/creator.py @@ -376,7 +376,7 @@ def get_submodel(_model: "Type[Model]") -> Optional[Type[PydanticModel]]: if model: if fdesc.get("nullable"): fconfig["nullable"] = True - if fdesc.get("nullable") or field_default is not None: + if fdesc.get("nullable") or field_default is not None or fname in optional: model = Optional[model] # type: ignore pannotations[fname] = model @@ -388,7 +388,12 @@ def get_submodel(_model: "Type[Model]") -> Optional[Type[PydanticModel]]: ): model = get_submodel(fdesc["python_type"]) if model: - pannotations[fname] = List[model] # type: ignore + if fdesc.get("nullable") or field_default is not None or fname in optional: + model = Optional[List[model]] # type: ignore + else: + model = List[model] # type: ignore + + pannotations[fname] = model # type: ignore # Computed fields as methods elif field_type is callable: