From 35471f19a2e1f9683f5ccf1c89ac4146b9c496dc Mon Sep 17 00:00:00 2001 From: Tsung-Ju Lii Date: Wed, 15 Nov 2023 15:00:50 +0800 Subject: [PATCH] fix pydantic v1 bug --- .../{{cookiecutter.project_name}}/tests/test_dummy.py | 5 +++++ .../web/api/dummy/schema.py | 10 +++++++--- 2 files changed, 12 insertions(+), 3 deletions(-) diff --git a/fastapi_template/template/{{cookiecutter.project_name}}/{{cookiecutter.project_name}}/tests/test_dummy.py b/fastapi_template/template/{{cookiecutter.project_name}}/{{cookiecutter.project_name}}/tests/test_dummy.py index cb18575..6065435 100644 --- a/fastapi_template/template/{{cookiecutter.project_name}}/{{cookiecutter.project_name}}/tests/test_dummy.py +++ b/fastapi_template/template/{{cookiecutter.project_name}}/{{cookiecutter.project_name}}/tests/test_dummy.py @@ -107,3 +107,8 @@ async def test_getting( assert response.status_code == status.HTTP_200_OK assert len(dummies) == 1 assert dummies[0]['name'] == test_name + + {%- if cookiecutter.orm == "beanie" %} + # Clean up the object we just inserted + await dao.delete_dummy_model_by_name(name=test_name) + {%- endif %} diff --git a/fastapi_template/template/{{cookiecutter.project_name}}/{{cookiecutter.project_name}}/web/api/dummy/schema.py b/fastapi_template/template/{{cookiecutter.project_name}}/{{cookiecutter.project_name}}/web/api/dummy/schema.py index bc2eef8..82238eb 100644 --- a/fastapi_template/template/{{cookiecutter.project_name}}/{{cookiecutter.project_name}}/web/api/dummy/schema.py +++ b/fastapi_template/template/{{cookiecutter.project_name}}/{{cookiecutter.project_name}}/web/api/dummy/schema.py @@ -6,7 +6,7 @@ {%- endif %} {%- if cookiecutter.db_info.name == "mongodb" %} {%- if cookiecutter.pydanticv1 == "True" %} -from pydantic import validator +from pydantic import validator, Field {%- else %} from pydantic import field_validator {%- endif %} @@ -24,17 +24,21 @@ class DummyModelDTO(BaseModel): {%- if cookiecutter.db_info.name != "mongodb" %} id: int {%- else %} + {%- if cookiecutter.pydanticv1 == "True" %} + id: str = Field(alias="_id") + {%- else %} id: str {%- endif %} + {%- endif %} name: str {%- if cookiecutter.db_info.name == "mongodb" %} {%- if cookiecutter.pydanticv1 == "True" %} - @validator("id") + @validator("id", pre=True) {%- else %} @field_validator("id", mode="before") - @classmethod {%- endif %} + @classmethod def parse_object_id(cls, document_id: ObjectId) -> str: """ Validator that converts `ObjectId` to json serializable `str`.