Skip to content

Commit

Permalink
fix: insert dataclass support
Browse files Browse the repository at this point in the history
  • Loading branch information
Goradii committed Nov 19, 2024
1 parent 8d29b38 commit 403f3c6
Showing 1 changed file with 14 additions and 2 deletions.
16 changes: 14 additions & 2 deletions sqladmin/_queries.py
Original file line number Diff line number Diff line change
Expand Up @@ -189,8 +189,20 @@ async def _delete_async(self, pk: str, request: Request) -> None:
await session.commit()
await self.model_view.after_model_delete(obj, request)

def _prepare_insert_dataclass(self, data: dict[str, Any]) -> dict[str, Any]:
try:
init = {
k: v
for k, v in data.items()
if self.model_view.model.__dataclass_fields__[k].init # type: ignore[attr-defined] # caught in except block
}
except AttributeError:
return {}
else:
return init

def _insert_sync(self, data: dict[str, Any], request: Request) -> Any:
obj = self.model_view.model()
obj = self.model_view.model(**self._prepare_insert_dataclass(data))

with self.model_view.session_maker(expire_on_commit=False) as session:
anyio.from_thread.run(
Expand All @@ -205,7 +217,7 @@ def _insert_sync(self, data: dict[str, Any], request: Request) -> Any:
return obj

async def _insert_async(self, data: dict[str, Any], request: Request) -> Any:
obj = self.model_view.model()
obj = self.model_view.model(**self._prepare_insert_dataclass(data))

async with self.model_view.session_maker(expire_on_commit=False) as session:
await self.model_view.on_model_change(data, obj, True, request)
Expand Down

0 comments on commit 403f3c6

Please sign in to comment.