Skip to content

Commit

Permalink
✨ Add support for excluding columns from Pydantic model (#3)
Browse files Browse the repository at this point in the history
  • Loading branch information
tiangolo authored May 5, 2020
1 parent 0fa3baf commit d4ba9b6
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 2 deletions.
6 changes: 4 additions & 2 deletions pydantic_sqlalchemy/main.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from typing import Type
from typing import Container, Type

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


def sqlalchemy_to_pydantic(
db_model: Type, *, config: Type = OrmConfig
db_model: Type, *, config: Type = OrmConfig, exclude: Container[str] = []
) -> Type[BaseModel]:
mapper = inspect(db_model)
fields = {}
Expand All @@ -20,6 +20,8 @@ def sqlalchemy_to_pydantic(
column = attr.columns[0]
python_type = column.type.python_type
name = attr.key
if name in exclude:
continue
default = column.default
if default is None and not column.nullable:
default = ...
Expand Down
21 changes: 21 additions & 0 deletions tests/test_pydantic_sqlalchemy.py
Original file line number Diff line number Diff line change
Expand Up @@ -108,3 +108,24 @@ class PydanticUserWithAddresses(PydanticUser):
{"emailAddress": "[email protected]", "id": 2, "userId": 1},
],
}


def test_exclude() -> None:
PydanticUser = sqlalchemy_to_pydantic(User, exclude={"nickname"})
PydanticAddress = sqlalchemy_to_pydantic(Address, exclude={"user_id"})

class PydanticUserWithAddresses(PydanticUser):
addresses: List[PydanticAddress] = []

user = db.query(User).first()
pydantic_user_with_addresses = PydanticUserWithAddresses.from_orm(user)
data = pydantic_user_with_addresses.dict(by_alias=True)
assert data == {
"fullname": "Ed Jones",
"id": 1,
"name": "ed",
"addresses": [
{"email_address": "[email protected]", "id": 1},
{"email_address": "[email protected]", "id": 2},
],
}

0 comments on commit d4ba9b6

Please sign in to comment.