dto
Using this implementation instead of the starlite.SQLAlchemy plugin DTO as
a POC for using the SQLAlchemy model type annotations to build the pydantic
model.
Also experimenting with marking columns for DTO purposes using the
SQLAlchemy.Column.info field, which allows demarcation of fields that
should always be private, or read-only at the model declaration layer.
Purpose ¶
Bases: Enum
For identifying the purpose of a DTO to the factory.
The factory will exclude fields marked as private or read-only on the domain model depending on the purpose of the DTO.
factory ¶
Create a pydantic model class from a SQLAlchemy declarative ORM class.
The fields that are included in the model can be controlled on the SQLAlchemy class
definition by including a "dto" key in the Column.info mapping. For example:
```python
class User(DeclarativeBase):
id: Mapped[UUID] = mapped_column(
default=uuid4, primary_key=True, info={"dto": dto.Mode.READ_ONLY}
)
email: Mapped[str]
password_hash: Mapped[str] = mapped_column(info={"dto": dto.Mode.PRIVATE})
```
In the above example, a DTO generated for Purpose.READ will include the id and email
fields, while a model generated for Purpose.WRITE will only include a field for email.
Notice that columns marked as Mode.PRIVATE will not have a field produced in any DTO object.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name |
str
|
Name given to the DTO class. |
required |
model |
type[DeclarativeBase]
|
The SQLAlchemy model class. |
required |
purpose |
Purpose
|
Is the DTO for write or read operations? |
required |
exclude |
set[str] | None
|
Explicitly exclude attributes from the DTO. |
None
|
Returns:
| Type | Description |
|---|---|
type[BaseModel]
|
A Pydantic model that includes only fields that are appropriate to |
type[BaseModel]
|
|