ultimate-fastapi-tutorial
ultimate-fastapi-tutorial copied to clipboard
json encoders date erro
First of all thanks for putting this tutorial together. Very helpful.
I came across an issue with the CRUDBase class when trying to create my own models.
If you have a date column, the jsonable_encode converts a datetime.date object to a str. This dosen't work when you pass the kwargs to the sqlalchemy model class.
def create(self, db: Session, *, obj_in: CreateSchemaType) -> ModelType:
obj_in_data = jsonable_encoder(obj_in)
db_obj = self.model(**obj_in_data) # type: ignore
db.add(db_obj)
db.commit()
db.refresh(db_obj)
return db_obj
TypeError: SQLite Date type only accepts Python date objects as input.
I fixed it by simply calling the .dict() method on the pydantic model.
def create(self, db: Session, *, obj_in: CreateSchemaType) -> ModelType:
db_obj = self.model(**obj_in.dict()) # type: ignore
db.add(db_obj)
db.commit()
db.refresh(db_obj)
return db_obj
I took a look at the documentation for FastAPI about jsonable_encoders and it mentioned that it's not really to be used with a date formats.
I'm just curious, what is the utility of jsonable_encoders, and why would you use it.