Top-level API

class marshmallow_sqlalchemy.SQLAlchemySchema(*args, **kwargs)[source]

Schema for a SQLAlchemy model or table. Use together with auto_field to 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_instance is set to True in 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.instance or loaded by primary key(s) in the data; else create a new row.

Parameters:

data – Data to deserialize.

Return type:

_ModelType

property session: Session | None

The SQLAlchemy session used to load models.

property transient: bool

Whether model instances are loaded in a transient state.

validate(data, *, session=None, **kwargs)

Same as marshmallow.Schema.validate but allows passing a session.

Parameters:
  • data (_LoadDataT)

  • session (Session | None)

Return type:

dict[str, list[str]]

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_instance is set to True in 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.instance or loaded by primary key(s) in the data; else create a new row.

Parameters:

data – Data to deserialize.

Return type:

_ModelType

property session: Session | None

The SQLAlchemy session used to load models.

property transient: bool

Whether model instances are loaded in a transient state.

validate(data, *, session=None, **kwargs)

Same as marshmallow.Schema.validate but allows passing a session.

Parameters:
  • data (_LoadDataT)

  • session (Session | None)

Return type:

dict[str, list[str]]

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.Field pairs for the given model. Note: SynonymProperties are ignored. Use an explicit field if you want to include a synonym.

Parameters:
  • model (type[DeclarativeMeta]) – The SQLAlchemy model

  • include_fk (bool) – Whether to include foreign key fields in the output.

  • include_relationships (bool) – Whether to include relationships fields in the output.

  • fields (Iterable[str] | None)

  • exclude (Iterable[str] | None)

  • base_fields (dict | None)

  • dict_cls (type[dict])

Returns:

dict of field_name: Field instance pairs

Return type:

dict[str, fields.Field]

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 Property to a field instance or class.

Parameters:
  • prop (Property) – SQLAlchemy Property.

  • instance (bool) – If True, return Field instance, computing relevant kwargs from the given property. If False, return the Field class.

  • kwargs – Additional keyword arguments to pass to the field constructor.

  • field_class (type[fields.Field] | None)

Returns:

A marshmallow.fields.Field class 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 Column to a field instance or class.

Parameters:
  • column (sqlalchemy.schema.Column) – SQLAlchemy Column.

  • instance (bool) – If True, return Field instance, computing relevant kwargs from the given property. If False, return the Field class.

Returns:

A marshmallow.fields.Field class or instance.

Return type:

Field | type[Field]

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 property2field

  • instance (bool)

  • field_class (type[fields.Field] | None)

Returns:

A marshmallow.fields.Field class 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 as SQLAlchemySchemaOpts, with the addition of:

  • include_fk: Whether to include foreign fields; defaults to False.

  • include_relationships: Whether to include relationships; defaults to False.

class marshmallow_sqlalchemy.SQLAlchemySchemaOpts(meta, *args, **kwargs)[source]

Options class for SQLAlchemySchema. Adds the following options:

  • model: The SQLAlchemy model to generate the Schema from (mutually exclusive with table).

  • table: The SQLAlchemy table to generate the Schema from (mutually exclusive with model).

  • load_instance: Whether to load model instances.

  • sqla_session: SQLAlchemy session to be used for deserialization.

    This is only needed when load_instance is True. You can also pass a session to the Schema’s load method.

  • transient: Whether to load model instances in a transient state (effectively ignoring the session).

    Only relevant when load_instance is True.

  • model_converter: ModelConverter class 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. If attribute is unspecified, attribute will be set to the same value as column_name.

  • model (type[DeclarativeMeta] | None) – Model to generate the field from. If None, uses model specified on class Meta.

  • table (sa.Table | None) – Table to generate the field from. If None, uses table specified on class Meta.

  • kwargs – Field argument overrides.

Return type:

SQLAlchemyAutoField

marshmallow_sqlalchemy.column2field(column, *, instance=True, **kwargs)

Convert a SQLAlchemy Column to a field instance or class.

Parameters:
  • column (sqlalchemy.schema.Column) – SQLAlchemy Column.

  • instance (bool) – If True, return Field instance, computing relevant kwargs from the given property. If False, return the Field class.

Returns:

A marshmallow.fields.Field class or instance.

Return type:

Field | type[Field]

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 property2field

  • instance (bool)

  • field_class (type[fields.Field] | None)

Returns:

A marshmallow.fields.Field class 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.Field pairs for the given model. Note: SynonymProperties are ignored. Use an explicit field if you want to include a synonym.

Parameters:
  • model (type[DeclarativeMeta]) – The SQLAlchemy model

  • include_fk (bool) – Whether to include foreign key fields in the output.

  • include_relationships (bool) – Whether to include relationships fields in the output.

  • fields (Iterable[str] | None)

  • exclude (Iterable[str] | None)

  • base_fields (dict | None)

  • dict_cls (type[dict])

Returns:

dict of field_name: Field instance pairs

Return type:

dict[str, fields.Field]

marshmallow_sqlalchemy.property2field(prop, *, instance=True, field_class=None, **kwargs)

Convert a SQLAlchemy Property to a field instance or class.

Parameters:
  • prop (Property) – SQLAlchemy Property.

  • instance (bool) – If True, return Field instance, computing relevant kwargs from the given property. If False, return the Field class.

  • kwargs – Additional keyword arguments to pass to the field constructor.

  • field_class (type[fields.Field] | None)

Returns:

A marshmallow.fields.Field class 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 a Schema class whose options includes a SQLAlchemy model, such as SQLAlchemySchema.

Parameters:
  • columns (list[str] | str | None) – Optional column names on related model. If not provided, the primary key(s) of the related model will be used.

  • column (str | None)

class marshmallow_sqlalchemy.fields.Nested(nested, *, only=None, exclude=(), many=None, unknown=None, **kwargs)[source]

Nested field that inherits the session from its parent.

Parameters:
  • nested (Schema | SchemaMeta | str | dict[str, Field] | Callable[[], Schema | SchemaMeta | dict[str, Field]])

  • only (types.StrSequenceOrSet | None)

  • exclude (types.StrSequenceOrSet)

  • many (bool | None)

  • unknown (types.UnknownOption | None)

  • kwargs (Unpack[_BaseFieldKwargs])