Skip to content

Commit

Permalink
more custom serialisation for datetime fields
Browse files Browse the repository at this point in the history
  • Loading branch information
dantownsend committed Oct 30, 2019
1 parent 8c2ee63 commit 8185fd0
Showing 1 changed file with 14 additions and 5 deletions.
19 changes: 14 additions & 5 deletions piccolo_api/crud/endpoints.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,10 +49,15 @@ def __init__(self, table: Table, read_only: bool = True) -> None:

###########################################################################

@property
def pydantic_model(self):
# TODO - improve caching here.
def _create_pydantic_model(self, include_default_columns=False):
columns: t.Dict[str, t.Any] = {}
for column in self.table._meta.non_default_columns:
piccolo_columns = (
self.table._meta.columns
if include_default_columns
else self.table._meta.non_default_columns
)
for column in piccolo_columns:
if type(column) == ForeignKey:
columns[column._meta.name] = pydantic.Schema(
default=0,
Expand All @@ -71,12 +76,16 @@ def pydantic_model(self):
**columns,
)

@property
def pydantic_model(self):
return self._create_pydantic_model()

@property
def pydantic_model_plural(self):
"""
This is for when we want to serialise many copies of the model.
"""
base_model = self.pydantic_model
base_model = self._create_pydantic_model(include_default_columns=True)
return pydantic.create_model(
str(self.table.__name__) + "Plural",
__config__=None,
Expand Down Expand Up @@ -203,7 +212,7 @@ async def _get_single(self, row_id: int):
except ValueError:
raise HTTPException(404, "Unable to find a row with that ID.")

return JSONResponse(row)
return CustomJSONResponse(self.pydantic_model(**row).json())

async def _put_single(self, row_id: int, data: t.Dict[str, t.Any]):
"""
Expand Down

0 comments on commit 8185fd0

Please sign in to comment.