From 114266bdd8739d6edfe30e82c31ee418f9ba633f Mon Sep 17 00:00:00 2001 From: Andrew Cherkashin <81467323+Spotika@users.noreply.github.com> Date: Fri, 20 Sep 2024 19:00:45 +0300 Subject: [PATCH] Fix: remove aliases for id field everywhere (#63) * fix: remove aliases for id field everywhere * fix: fix response serialize --- src/db/methods/users.py | 2 +- src/db/types/types.py | 5 ++--- src/utils/schemas.py | 13 +++++++++++-- 3 files changed, 14 insertions(+), 6 deletions(-) diff --git a/src/db/methods/users.py b/src/db/methods/users.py index b44b775..eac00ce 100644 --- a/src/db/methods/users.py +++ b/src/db/methods/users.py @@ -23,6 +23,6 @@ def insert_user_with_id(user: types.UserWithoutID) -> int | None: Inserted user id or None, if error occurred """ try: - return insert_with_auto_increment_id(users, user.model_dump()) + return insert_with_auto_increment_id(users, user.db_dump()) except DuplicateKeyError: return None diff --git a/src/db/types/types.py b/src/db/types/types.py index 33044be..0159313 100644 --- a/src/db/types/types.py +++ b/src/db/types/types.py @@ -1,5 +1,4 @@ from typing import Literal -from pydantic import Field from utils.schemas import BaseModel @@ -13,7 +12,7 @@ class JWTPair(BaseModel): class Entity(BaseModel): - id: str = Field(alias="_id") + id: str target_type: EntityTargetType target_id: int @@ -31,4 +30,4 @@ class UserWithoutID(_UserBase): ... class User(_UserBase): - id: int = Field(alias="_id") + id: int diff --git a/src/utils/schemas.py b/src/utils/schemas.py index fda0bdb..1484d73 100644 --- a/src/utils/schemas.py +++ b/src/utils/schemas.py @@ -3,5 +3,14 @@ class BaseModel(pydantic.BaseModel): - def model_dump(self, by_alias=True, **kwargs) -> dict[str, Any]: - return super().model_dump(by_alias=by_alias, **kwargs) + def db_dump(self, by_alias=True, **kwargs) -> dict[str, Any]: + result = self.model_dump(by_alias=by_alias, **kwargs) + if "id" in result: + result["_id"] = result.pop("id") + return result + + @pydantic.model_validator(mode="before") + def convert_id(cls, values): + if "_id" in values: + values["id"] = str(values.pop("_id")) + return values