Top-level API¶
- class marshmallow_sqlalchemy.SQLAlchemySchema(*args, **kwargs)[source]¶
Schema for a SQLAlchemy model or table. Use together with
auto_fieldto generate fields from columns.Example:
from marshmallow_sqlalchemy import SQLAlchemySchema, auto_field from mymodels import User class UserSchema(SQLAlchemySchema): class Meta: model = User id = auto_field() created_at = auto_field(dump_only=True) name = auto_field()
- get_instance(data)¶
Retrieve an existing record by primary key(s). If the schema instance is transient, return
None.- Parameters:
data – Serialized data to inform lookup.
- Return type:
_ModelType | None
- load(data, *, session=None, instance=None, transient=False, **kwargs)¶
Deserialize data. If
load_instanceis set toTruein the schema meta options, load the data as model instance(s).- Parameters:
data (_LoadDataT) – The data to deserialize.
session (Session | None) – SQLAlchemy
session.instance (_ModelType | None) – Existing model instance to modify.
transient (bool) – If
True, load transient model instance(s).kwargs – Same keyword arguments as
marshmallow.Schema.load.
- Return type:
Any
- make_instance(data, **kwargs)¶
Deserialize data to an instance of the model if self.load_instance is True.
Update an existing row if specified in
self.instanceor loaded by primary key(s) in the data; else create a new row.- Parameters:
data – Data to deserialize.
- Return type:
_ModelType
- class marshmallow_sqlalchemy.SQLAlchemyAutoSchema(*args, **kwargs)[source]¶
- Schema that automatically generates fields from the columns of
a SQLAlchemy model or table.
Example:
from marshmallow_sqlalchemy import SQLAlchemyAutoSchema, auto_field from mymodels import User class UserSchema(SQLAlchemyAutoSchema): class Meta: model = User # OR # table = User.__table__ created_at = auto_field(dump_only=True)
- get_instance(data)¶
Retrieve an existing record by primary key(s). If the schema instance is transient, return
None.- Parameters:
data – Serialized data to inform lookup.
- Return type:
_ModelType | None
- load(data, *, session=None, instance=None, transient=False, **kwargs)¶
Deserialize data. If
load_instanceis set toTruein the schema meta options, load the data as model instance(s).- Parameters:
data (_LoadDataT) – The data to deserialize.
session (Session | None) – SQLAlchemy
session.instance (_ModelType | None) – Existing model instance to modify.
transient (bool) – If
True, load transient model instance(s).kwargs – Same keyword arguments as
marshmallow.Schema.load.
- Return type:
Any
- make_instance(data, **kwargs)¶
Deserialize data to an instance of the model if self.load_instance is True.
Update an existing row if specified in
self.instanceor loaded by primary key(s) in the data; else create a new row.- Parameters:
data – Data to deserialize.
- Return type:
_ModelType
- exception marshmallow_sqlalchemy.ModelConversionError[source]¶
Raised when an error occurs in converting a SQLAlchemy construct to a marshmallow object.
- class marshmallow_sqlalchemy.ModelConverter(schema_cls=None)[source]¶
Converts a SQLAlchemy model into a dictionary of corresponding marshmallow
Fields.- Parameters:
schema_cls (type[ma.Schema] | None)
- fields_for_model(model, *, include_fk=False, include_relationships=False, fields=None, exclude=None, base_fields=None, dict_cls=<class 'dict'>)[source]¶
Generate a dict of field_name:
marshmallow.fields.Fieldpairs for the given model. Note: SynonymProperties are ignored. Use an explicit field if you want to include a synonym.- Parameters:
- Returns:
dict of field_name: Field instance pairs
- Return type:
- property2field(prop: MapperProperty, *, instance: Literal[True] = True, field_class: type[Field] | None = None, **kwargs) Field[source]¶
- property2field(prop: MapperProperty, *, instance: Literal[False] = True, field_class: type[Field] | None = None, **kwargs) type[Field]
Convert a SQLAlchemy
Propertyto a field instance or class.- Parameters:
- Returns:
A
marshmallow.fields.Fieldclass or instance.- Return type:
fields.Field | type[fields.Field]
- column2field(column, *, instance: Literal[True] = True, **kwargs) Field[source]¶
- column2field(column, *, instance: Literal[False] = True, **kwargs) type[Field]
Convert a SQLAlchemy
Columnto a field instance or class.- Parameters:
column (sqlalchemy.schema.Column) – SQLAlchemy Column.
instance (bool) – If
True, returnFieldinstance, computing relevant kwargs from the given property. IfFalse, return theFieldclass.
- Returns:
A
marshmallow.fields.Fieldclass or instance.- Return type:
- field_for(model: type[DeclarativeMeta], property_name: str, *, instance: Literal[True] = True, field_class: type[Field] | None = None, **kwargs) Field[source]¶
- field_for(model: type[DeclarativeMeta], property_name: str, *, instance: Literal[False] = True, field_class: type[Field] | None = None, **kwargs) type[Field]
Convert a property for a mapped SQLAlchemy class to a marshmallow
Field. Example:date_created = field_for(Author, "date_created", dump_only=True) author = field_for(Book, "author")
- Parameters:
model (type) – A SQLAlchemy mapped class.
property_name (str) – The name of the property to convert.
kwargs – Extra keyword arguments to pass to
property2fieldinstance (bool)
field_class (type[fields.Field] | None)
- Returns:
A
marshmallow.fields.Fieldclass or instance.- Return type:
fields.Field | type[fields.Field]
- class marshmallow_sqlalchemy.SQLAlchemyAutoSchemaOpts(meta, *args, **kwargs)[source]¶
Options class for
SQLAlchemyAutoSchema. Has the same options asSQLAlchemySchemaOpts, with the addition of:
- class marshmallow_sqlalchemy.SQLAlchemySchemaOpts(meta, *args, **kwargs)[source]¶
Options class for
SQLAlchemySchema. Adds the following options:model: The SQLAlchemy model to generate theSchemafrom (mutually exclusive withtable).table: The SQLAlchemy table to generate theSchemafrom (mutually exclusive withmodel).load_instance: Whether to load model instances.sqla_session: SQLAlchemy session to be used for deserialization.This is only needed when
load_instanceisTrue. You can also pass a session to the Schema’sloadmethod.
transient: Whether to load model instances in a transient state (effectively ignoring the session).Only relevant when
load_instanceisTrue.
model_converter:ModelConverterclass to use for converting the SQLAlchemy model to marshmallow fields.
- marshmallow_sqlalchemy.auto_field(column_name=None, *, model=None, table=None, **kwargs)[source]¶
Mark a field to autogenerate from a model or table.
- Parameters:
column_name (str | None) – Name of the column to generate the field from. If
None, matches the field name. Ifattributeis unspecified,attributewill be set to the same value ascolumn_name.model (type[DeclarativeMeta] | None) – Model to generate the field from. If
None, usesmodelspecified onclass Meta.table (sa.Table | None) – Table to generate the field from. If
None, usestablespecified onclass Meta.kwargs – Field argument overrides.
- Return type:
SQLAlchemyAutoField
- marshmallow_sqlalchemy.column2field(column, *, instance=True, **kwargs)¶
Convert a SQLAlchemy
Columnto a field instance or class.- Parameters:
column (sqlalchemy.schema.Column) – SQLAlchemy Column.
instance (bool) – If
True, returnFieldinstance, computing relevant kwargs from the given property. IfFalse, return theFieldclass.
- Returns:
A
marshmallow.fields.Fieldclass or instance.- Return type:
- marshmallow_sqlalchemy.field_for(model, property_name, *, instance=True, field_class=None, **kwargs)¶
Convert a property for a mapped SQLAlchemy class to a marshmallow
Field. Example:date_created = field_for(Author, "date_created", dump_only=True) author = field_for(Book, "author")
- Parameters:
model (type) – A SQLAlchemy mapped class.
property_name (str) – The name of the property to convert.
kwargs – Extra keyword arguments to pass to
property2fieldinstance (bool)
field_class (type[fields.Field] | None)
- Returns:
A
marshmallow.fields.Fieldclass or instance.- Return type:
fields.Field | type[fields.Field]
- marshmallow_sqlalchemy.fields_for_model(model, *, include_fk=False, include_relationships=False, fields=None, exclude=None, base_fields=None, dict_cls=<class 'dict'>)¶
Generate a dict of field_name:
marshmallow.fields.Fieldpairs for the given model. Note: SynonymProperties are ignored. Use an explicit field if you want to include a synonym.- Parameters:
- Returns:
dict of field_name: Field instance pairs
- Return type:
- marshmallow_sqlalchemy.property2field(prop, *, instance=True, field_class=None, **kwargs)¶
Convert a SQLAlchemy
Propertyto a field instance or class.- Parameters:
- Returns:
A
marshmallow.fields.Fieldclass or instance.- Return type:
fields.Field | type[fields.Field]
Fields¶
- class marshmallow_sqlalchemy.fields.RelatedList(cls_or_instance, **kwargs)[source]¶
- Parameters:
cls_or_instance (Field[_InternalT] | type[Field[_InternalT]])
kwargs (Unpack[_BaseFieldKwargs])
- class marshmallow_sqlalchemy.fields.Related(columns=None, column=None, **kwargs)[source]¶
Related data represented by a SQLAlchemy
relationship. Must be attached to aSchemaclass whose options includes a SQLAlchemymodel, such asSQLAlchemySchema.