Pydantic documentation Fixes #1829 (#1871)

- Improved the `sqlalchemy_to_pydantic` function to accept additional schema fields on top of the SQLAlchemy model fields
- Added the solves and solved_by_me fields to the Swagger documentation (Closes #1829)
This commit is contained in:
Ife Lawal
2021-04-26 14:00:04 -04:00
committed by GitHub
parent 21af356642
commit 03e546e9f0
2 changed files with 9 additions and 3 deletions

View File

@@ -62,7 +62,9 @@ challenges_namespace = Namespace(
"challenges", description="Endpoint to retrieve Challenges"
)
ChallengeModel = sqlalchemy_to_pydantic(Challenges)
ChallengeModel = sqlalchemy_to_pydantic(
Challenges, include={"solves": int, "solved_by_me": bool}
)
TransientChallengeModel = sqlalchemy_to_pydantic(Challenges, exclude=["id"])

View File

@@ -1,4 +1,4 @@
from typing import Container, Type
from typing import Container, Dict, Type
from pydantic import BaseModel, create_model
from sqlalchemy.inspection import inspect
@@ -6,7 +6,7 @@ from sqlalchemy.orm.properties import ColumnProperty
def sqlalchemy_to_pydantic(
db_model: Type, *, exclude: Container[str] = None
db_model: Type, *, include: Dict[str, type] = None, exclude: Container[str] = None
) -> Type[BaseModel]:
"""
Mostly copied from https://github.com/tiangolo/pydantic-sqlalchemy
@@ -27,6 +27,10 @@ def sqlalchemy_to_pydantic(
if column.default is None and not column.nullable:
default = ...
fields[name] = (python_type, default)
if bool(include):
for name, python_type in include.items():
default = None
fields[name] = (python_type, default)
pydantic_model = create_model(
db_model.__name__, **fields # type: ignore
)