Skip to content

Commit d4ba9b6

Browse files
authored
✨ Add support for excluding columns from Pydantic model (tiangolo#3)
1 parent 0fa3baf commit d4ba9b6

File tree

2 files changed

+25
-2
lines changed

2 files changed

+25
-2
lines changed

pydantic_sqlalchemy/main.py

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
from typing import Type
1+
from typing import Container, Type
22

33
from pydantic import BaseConfig, BaseModel, create_model
44
from sqlalchemy.inspection import inspect
@@ -10,7 +10,7 @@ class OrmConfig(BaseConfig):
1010

1111

1212
def sqlalchemy_to_pydantic(
13-
db_model: Type, *, config: Type = OrmConfig
13+
db_model: Type, *, config: Type = OrmConfig, exclude: Container[str] = []
1414
) -> Type[BaseModel]:
1515
mapper = inspect(db_model)
1616
fields = {}
@@ -20,6 +20,8 @@ def sqlalchemy_to_pydantic(
2020
column = attr.columns[0]
2121
python_type = column.type.python_type
2222
name = attr.key
23+
if name in exclude:
24+
continue
2325
default = column.default
2426
if default is None and not column.nullable:
2527
default = ...

tests/test_pydantic_sqlalchemy.py

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -108,3 +108,24 @@ class PydanticUserWithAddresses(PydanticUser):
108108
{"emailAddress": "eddy@example.com", "id": 2, "userId": 1},
109109
],
110110
}
111+
112+
113+
def test_exclude() -> None:
114+
PydanticUser = sqlalchemy_to_pydantic(User, exclude={"nickname"})
115+
PydanticAddress = sqlalchemy_to_pydantic(Address, exclude={"user_id"})
116+
117+
class PydanticUserWithAddresses(PydanticUser):
118+
addresses: List[PydanticAddress] = []
119+
120+
user = db.query(User).first()
121+
pydantic_user_with_addresses = PydanticUserWithAddresses.from_orm(user)
122+
data = pydantic_user_with_addresses.dict(by_alias=True)
123+
assert data == {
124+
"fullname": "Ed Jones",
125+
"id": 1,
126+
"name": "ed",
127+
"addresses": [
128+
{"email_address": "ed@example.com", "id": 1},
129+
{"email_address": "eddy@example.com", "id": 2},
130+
],
131+
}

0 commit comments

Comments
 (0)