0
# Schema Generation
1
2
Schema generation capabilities in marshmallow-sqlalchemy, providing two approaches for creating marshmallow schemas from SQLAlchemy models: automatic generation and manual field declaration.
3
4
## Capabilities
5
6
### SQLAlchemySchema
7
8
Base schema class for manual field declaration using `auto_field()` to specify which model columns to include and how to configure them.
9
10
```python { .api }
11
class SQLAlchemySchema(LoadInstanceMixin.Schema[_ModelType], Schema):
12
"""Schema for SQLAlchemy model or table with manual field declaration.
13
14
Use with auto_field() to generate fields from columns.
15
"""
16
OPTIONS_CLASS = SQLAlchemySchemaOpts
17
```
18
19
#### Usage Example
20
21
```python
22
from marshmallow_sqlalchemy import SQLAlchemySchema, auto_field
23
from mymodels import User
24
25
class UserSchema(SQLAlchemySchema):
26
class Meta:
27
model = User
28
load_instance = True
29
sqla_session = session
30
31
id = auto_field(dump_only=True)
32
username = auto_field()
33
email = auto_field()
34
created_at = auto_field(dump_only=True)
35
36
# Custom field with overrides
37
password_hash = auto_field(column_name="password", load_only=True)
38
```
39
40
### SQLAlchemyAutoSchema
41
42
Schema that automatically generates fields from all columns in a SQLAlchemy model or table, with options to control field inclusion.
43
44
```python { .api }
45
class SQLAlchemyAutoSchema(SQLAlchemySchema[_ModelType]):
46
"""Schema that automatically generates fields from model columns.
47
48
Generates fields for all columns unless explicitly excluded.
49
"""
50
OPTIONS_CLASS = SQLAlchemyAutoSchemaOpts
51
```
52
53
#### Usage Example
54
55
```python
56
from marshmallow_sqlalchemy import SQLAlchemyAutoSchema
57
from mymodels import User, Post
58
59
class UserAutoSchema(SQLAlchemyAutoSchema):
60
class Meta:
61
model = User
62
load_instance = True
63
include_relationships = True
64
include_fk = False
65
exclude = ["password_hash"]
66
67
# Can still override specific fields
68
created_at = auto_field(dump_only=True)
69
70
class PostAutoSchema(SQLAlchemyAutoSchema):
71
class Meta:
72
table = Post.__table__ # Can use table instead of model
73
fields = ["id", "title", "content"] # Only include these fields
74
```
75
76
### auto_field Function
77
78
Function to mark a field for automatic generation from a model or table column, with support for field customization.
79
80
```python { .api }
81
def auto_field(
82
column_name: str | None = None,
83
*,
84
model: type[DeclarativeMeta] | None = None,
85
table: sa.Table | None = None,
86
**kwargs
87
) -> SQLAlchemyAutoField:
88
"""Mark a field to autogenerate from a model or table.
89
90
Parameters:
91
- column_name: Name of column to generate field from. If None, matches field name
92
- model: Model to generate field from. If None, uses model from class Meta
93
- table: Table to generate field from. If None, uses table from class Meta
94
- **kwargs: Field argument overrides (dump_only, load_only, validate, etc.)
95
96
Returns:
97
SQLAlchemyAutoField instance for metaclass processing
98
"""
99
```
100
101
#### Usage Examples
102
103
```python
104
class UserSchema(SQLAlchemySchema):
105
class Meta:
106
model = User
107
108
# Basic auto field - maps to column with same name
109
username = auto_field()
110
111
# Map to different column name
112
user_email = auto_field(column_name="email")
113
114
# Add field-specific options
115
created_at = auto_field(dump_only=True)
116
password = auto_field(load_only=True, validate=validate.Length(min=8))
117
118
# Use different model
119
profile_data = auto_field(column_name="data", model=UserProfile)
120
```
121
122
### Schema Options
123
124
Configuration classes that control schema behavior and field generation.
125
126
#### SQLAlchemySchemaOpts
127
128
```python { .api }
129
class SQLAlchemySchemaOpts(LoadInstanceMixin.Opts, SchemaOpts):
130
"""Options class for SQLAlchemySchema.
131
132
Attributes:
133
- model: SQLAlchemy model to generate schema from (mutually exclusive with table)
134
- table: SQLAlchemy table to generate schema from (mutually exclusive with model)
135
- load_instance: Whether to load model instances (default: False)
136
- sqla_session: SQLAlchemy session for deserialization
137
- transient: Whether to load instances in transient state (default: False)
138
- model_converter: ModelConverter class to use (default: ModelConverter)
139
"""
140
model: type[DeclarativeMeta] | None
141
table: sa.Table | None
142
load_instance: bool
143
sqla_session: Session | None
144
transient: bool
145
model_converter: type[ModelConverter]
146
```
147
148
#### SQLAlchemyAutoSchemaOpts
149
150
```python { .api }
151
class SQLAlchemyAutoSchemaOpts(SQLAlchemySchemaOpts):
152
"""Options class for SQLAlchemyAutoSchema.
153
154
Additional attributes:
155
- include_fk: Whether to include foreign key fields (default: False)
156
- include_relationships: Whether to include relationships (default: False)
157
"""
158
include_fk: bool
159
include_relationships: bool
160
```
161
162
#### Meta Configuration Examples
163
164
```python
165
class UserSchema(SQLAlchemyAutoSchema):
166
class Meta:
167
# Model specification (choose one)
168
model = User # Use SQLAlchemy model
169
# OR
170
table = User.__table__ # Use table directly
171
172
# Instance loading
173
load_instance = True # Load as model instances
174
sqla_session = session # Session for loading
175
transient = False # Load persistent instances
176
177
# Field inclusion/exclusion
178
include_fk = True # Include foreign key fields
179
include_relationships = True # Include relationship fields
180
fields = ["id", "name"] # Only include these fields
181
exclude = ["password"] # Exclude these fields
182
183
# Custom converter
184
model_converter = CustomModelConverter
185
```
186
187
### Loading Instances
188
189
When `load_instance=True`, schemas can deserialize data directly into SQLAlchemy model instances.
190
191
```python
192
# Configure schema for instance loading
193
class UserSchema(SQLAlchemyAutoSchema):
194
class Meta:
195
model = User
196
load_instance = True
197
198
schema = UserSchema()
199
200
# Load as dictionary (default)
201
user_dict = schema.load({"name": "John", "email": "john@example.com"})
202
203
# Load as model instance
204
user_instance = schema.load(
205
{"name": "John", "email": "john@example.com"},
206
session=session
207
)
208
209
# Update existing instance
210
existing_user = session.get(User, 1)
211
updated_user = schema.load(
212
{"name": "Johnny"},
213
session=session,
214
instance=existing_user
215
)
216
217
# Load transient instance (not attached to session)
218
transient_user = schema.load(
219
{"name": "Jane"},
220
session=session,
221
transient=True
222
)
223
```