API Reference


marshmallow_sqlalchemy.fields_for_model =func(...)
marshmallow_sqlalchemy.property2field =func(...)
marshmallow_sqlalchemy.column2field =func(...)
marshmallow_sqlalchemy.field_for =func(...)
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]

Class that converts a SQLAlchemy model into a dictionary of corresponding marshmallow Fields.

class marshmallow_sqlalchemy.SQLAlchemyAutoSchema(*args, **kwargs)[source]
Schema that automatically generates fields from the columns of

a SQLAlchemy model or table.


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)

alias of SQLAlchemyAutoSchemaOpts

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.SQLAlchemySchema(*args, **kwargs)[source]

Schema for a SQLAlchemy model or table. Use together with auto_field to generate fields from columns.


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()

alias of SQLAlchemySchemaOpts

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: str = None, *, model: DeclarativeMeta = None, table: Table = None, **kwargs)[source]

Mark a field to autogenerate from a model or table.

  • column_name – 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 – Model to generate the field from. If None, uses model specified on class Meta.

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

  • kwargs – Field argument overrides.


class marshmallow_sqlalchemy.fields.Nested(nested: ~marshmallow.base.SchemaABC | type | str | dict[str, ~marshmallow.fields.Field | type] | ~typing.Callable[[], ~marshmallow.base.SchemaABC | type | dict[str, ~marshmallow.fields.Field | type]], *, dump_default: ~typing.Any = <marshmallow.missing>, default: ~typing.Any = <marshmallow.missing>, only: ~typing.Sequence[str] | ~typing.AbstractSet[str] | None = None, exclude: ~typing.Sequence[str] | ~typing.AbstractSet[str] = (), many: bool = False, unknown: str | None = None, **kwargs)[source]

Nested field that inherits the session from its parent.

_deserialize(*args, **kwargs)[source]

Same as Field._deserialize() with additional partial argument.


partial (bool|tuple) – For nested schemas, the partial parameter passed to Schema.load.

Changed in version 3.0.0: Add partial parameter.

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.


columns (list) – Optional column names on related model. If not provided, the primary key(s) of the related model will be used.

_deserialize(value, *args, **kwargs)[source]

Deserialize a serialized value to a model instance.

If the parent schema is transient, create a new (transient) instance. Otherwise, attempt to find an existing instance in the database. :param value: The value to deserialize.

_get_existing_instance(related_model, value)[source]

Retrieve the related object from an existing instance in the DB.

  • related_model – The related model to query

  • value – The serialized value to mapto an existing instance.


NoResultFound – if there is no matching record.

_serialize(value, attr, obj)[source]

Serializes value to a basic Python datatype. Noop by default. Concrete Field classes should implement this method.


class TitleCase(Field):
    def _serialize(self, value, attr, obj, **kwargs):
        if not value:
            return ''
        return str(value).title()
  • value – The value to be serialized.

  • attr (str) – The attribute or key on the object to be serialized.

  • obj (object) – The object the value was pulled from.

  • kwargs (dict) – Field-specific keyword arguments.


The serialized value

default_error_messages = {'invalid': 'Could not deserialize related value {value!r}; expected a dictionary with keys {keys!r}'}

Default error messages for various kinds of errors. The keys in this dictionary are passed to Field.make_error. The values are error messages passed to marshmallow.exceptions.ValidationError.

class marshmallow_sqlalchemy.fields.RelatedList(cls_or_instance: Field | type, **kwargs)[source]
get_value(obj, attr, accessor=None)[source]

Return the value for a given key from an object.

  • obj (object) – The object to get the value from.

  • attr (str) – The attribute/key in obj to get the value from.

  • accessor (callable) – A callable used to retrieve the value of attr from the object obj. Defaults to marshmallow.utils.get_value.


Get primary key properties for a SQLAlchemy model.


model – SQLAlchemy model class