Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add support for excluding columns from Pydantic model #3

Merged
merged 1 commit into from
May 5, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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},
],
}