From bc8052a196e9e9e574acad17e2c4ab02666a17b9 Mon Sep 17 00:00:00 2001 From: Gabriel Soicher Date: Wed, 27 Oct 2021 09:18:17 +0200 Subject: [PATCH] Add read_with_orm_mode for dataclasses This allows for a workaround for SQLAlchemy dataclasses after the changes introduced in 0.67 . It replicates the funcionality provided for Pydantic models (`read_with_orm_mode`) by allowing a special property to be set on dataclasses that want to opt in to the feature. --- fastapi/routing.py | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/fastapi/routing.py b/fastapi/routing.py index 63ad72964..607410e0b 100644 --- a/fastapi/routing.py +++ b/fastapi/routing.py @@ -99,6 +99,11 @@ def _prepare_response_content( for k, v in res.items() } elif dataclasses.is_dataclass(res): + # Allow dataclasses to specify the same read_with_orm_mode property as + # Pydantic models above + read_with_orm_mode = getattr(res, "__read_with_orm_mode__", None) + if read_with_orm_mode: + return res return dataclasses.asdict(res) return res