File tree Expand file tree Collapse file tree 2 files changed +33
-0
lines changed Expand file tree Collapse file tree 2 files changed +33
-0
lines changed Original file line number Diff line number Diff line change
1
+ from importlib_metadata import version
2
+
3
+ __version__ = version (__package__ )
4
+
5
+ from .main import sqlalchemy_to_pydantic
Original file line number Diff line number Diff line change
1
+ from typing import Type
2
+
3
+ from pydantic import BaseConfig , BaseModel , create_model
4
+ from sqlalchemy .inspection import inspect
5
+ from sqlalchemy .orm .properties import ColumnProperty
6
+
7
+
8
+ class OrmConfig (BaseConfig ):
9
+ orm_config = True
10
+
11
+
12
+ def sqlalchemy_to_pydantic (db_model : Type ) -> Type [BaseModel ]:
13
+ mapper = inspect (db_model )
14
+ fields = {}
15
+ for attr in mapper .attrs :
16
+ if isinstance (attr , ColumnProperty ):
17
+ if attr .columns :
18
+ column = attr .columns [0 ]
19
+ python_type = column .type .python_type
20
+ name = attr .key
21
+ default = column .default
22
+ if default is None and not column .nullable :
23
+ default = ...
24
+ fields [name ] = (python_type , default )
25
+ pydantic_model = create_model (
26
+ db_model .__name__ , __config__ = OrmConfig , ** fields # type: ignore
27
+ )
28
+ return pydantic_model
You can’t perform that action at this time.
0 commit comments