0
# marshmallow-sqlalchemy
1
2
SQLAlchemy integration with the marshmallow (de)serialization library. This package provides seamless integration between SQLAlchemy ORM models and marshmallow serialization/deserialization schemas, enabling automatic generation of marshmallow schemas from SQLAlchemy models with support for relationships, foreign keys, and field validation.
3
4
## Package Information
5
6
- **Package Name**: marshmallow-sqlalchemy
7
- **Package Type**: pypi
8
- **Language**: Python
9
- **Installation**: `pip install marshmallow-sqlalchemy`
10
11
## Core Imports
12
13
```python
14
from marshmallow_sqlalchemy import SQLAlchemySchema, SQLAlchemyAutoSchema, auto_field
15
```
16
17
For field conversion utilities:
18
19
```python
20
from marshmallow_sqlalchemy import ModelConverter, fields_for_model, field_for
21
```
22
23
For relationship fields:
24
25
```python
26
from marshmallow_sqlalchemy import Related, RelatedList, Nested
27
```
28
29
## Basic Usage
30
31
```python
32
import sqlalchemy as sa
33
from sqlalchemy.orm import DeclarativeBase, sessionmaker
34
from marshmallow_sqlalchemy import SQLAlchemyAutoSchema, SQLAlchemySchema, auto_field
35
36
# Define SQLAlchemy model
37
class Base(DeclarativeBase):
38
pass
39
40
class Author(Base):
41
__tablename__ = "authors"
42
id = sa.Column(sa.Integer, primary_key=True)
43
name = sa.Column(sa.String, nullable=False)
44
email = sa.Column(sa.String, unique=True)
45
46
# Automatic schema generation
47
class AuthorAutoSchema(SQLAlchemyAutoSchema):
48
class Meta:
49
model = Author
50
load_instance = True
51
52
# Manual schema with auto_field
53
class AuthorManualSchema(SQLAlchemySchema):
54
class Meta:
55
model = Author
56
load_instance = True
57
58
id = auto_field()
59
name = auto_field()
60
email = auto_field(dump_only=True)
61
62
# Usage
63
engine = sa.create_engine("sqlite:///:memory:")
64
Session = sessionmaker(engine)
65
session = Session()
66
67
schema = AuthorAutoSchema()
68
author_data = {"name": "John Doe", "email": "john@example.com"}
69
70
# Deserialize to dict
71
result = schema.load(author_data)
72
73
# Deserialize to model instance
74
author_instance = schema.load(author_data, session=session)
75
```
76
77
## Architecture
78
79
marshmallow-sqlalchemy uses a layered architecture:
80
81
- **Schema Layer**: `SQLAlchemySchema` and `SQLAlchemyAutoSchema` provide the main schema classes
82
- **Conversion Layer**: `ModelConverter` handles translation between SQLAlchemy types and marshmallow fields
83
- **Field Layer**: Specialized fields like `Related` and `RelatedList` handle SQLAlchemy relationships
84
- **Loading Layer**: `LoadInstanceMixin` provides model instance loading capabilities
85
86
This design enables bidirectional data transformation between SQLAlchemy model instances and JSON/dictionary representations, with automatic field type inference from database column definitions.
87
88
## Capabilities
89
90
### Schema Generation
91
92
Two approaches for creating schemas from SQLAlchemy models: automatic generation with `SQLAlchemyAutoSchema` and manual field declaration with `SQLAlchemySchema` and `auto_field`.
93
94
```python { .api }
95
class SQLAlchemySchema(LoadInstanceMixin.Schema, Schema):
96
"""Schema for SQLAlchemy model or table with manual field declaration."""
97
98
class SQLAlchemyAutoSchema(SQLAlchemySchema):
99
"""Schema that automatically generates fields from model columns."""
100
101
def auto_field(
102
column_name: str | None = None,
103
*,
104
model: type[DeclarativeMeta] | None = None,
105
table: sa.Table | None = None,
106
**kwargs
107
) -> SQLAlchemyAutoField:
108
"""Mark a field to autogenerate from a model or table."""
109
```
110
111
[Schema Generation](./schemas.md)
112
113
### Field Conversion
114
115
Comprehensive system for converting SQLAlchemy columns and properties to appropriate marshmallow fields, with support for all standard and database-specific types.
116
117
```python { .api }
118
class ModelConverter:
119
"""Converts SQLAlchemy models into marshmallow fields."""
120
121
def fields_for_model(
122
self,
123
model: type[DeclarativeMeta],
124
*,
125
include_fk: bool = False,
126
include_relationships: bool = False,
127
fields: Iterable[str] | None = None,
128
exclude: Iterable[str] | None = None,
129
base_fields: dict | None = None,
130
dict_cls: type[dict] = dict,
131
) -> dict[str, fields.Field]: ...
132
133
def fields_for_model(model, **kwargs) -> dict[str, fields.Field]: ...
134
def field_for(model, property_name: str, **kwargs) -> fields.Field: ...
135
```
136
137
[Field Conversion](./field-conversion.md)
138
139
### Relationship Handling
140
141
Specialized fields for handling SQLAlchemy relationships with automatic serialization/deserialization of related model instances.
142
143
```python { .api }
144
class Related(fields.Field):
145
"""Field for SQLAlchemy relationships."""
146
147
class RelatedList(fields.List):
148
"""List field for one-to-many and many-to-many relationships."""
149
```
150
151
[Relationship Fields](./relationship-fields.md)
152
153
## Types
154
155
```python { .api }
156
class SQLAlchemySchemaOpts(LoadInstanceMixin.Opts, SchemaOpts):
157
"""Options class for SQLAlchemySchema."""
158
model: type[DeclarativeMeta] | None
159
table: sa.Table | None
160
load_instance: bool
161
sqla_session: Session | None
162
transient: bool
163
model_converter: type[ModelConverter]
164
165
class SQLAlchemyAutoSchemaOpts(SQLAlchemySchemaOpts):
166
"""Options class for SQLAlchemyAutoSchema."""
167
include_fk: bool
168
include_relationships: bool
169
170
class MarshmallowSQLAlchemyError(Exception):
171
"""Base exception class from which all exceptions related to marshmallow-sqlalchemy inherit."""
172
173
class ModelConversionError(MarshmallowSQLAlchemyError):
174
"""Raised when an error occurs in converting a SQLAlchemy construct to a marshmallow object."""
175
176
class IncorrectSchemaTypeError(ModelConversionError):
177
"""Raised when a SQLAlchemyAutoField is bound to Schema that is not an instance of SQLAlchemySchema."""
178
```