API Reference

Core

marshmallow_sqlalchemy.fields_for_model =func(...)
marshmallow_sqlalchemy.property2field =func(...)
marshmallow_sqlalchemy.column2field =func(...)
marshmallow_sqlalchemy.field_for =func(...)
class marshmallow_sqlalchemy.TableSchema(*, only: Union[Sequence[str], Set[str]] = None, exclude: Union[Sequence[str], Set[str]] = (), many: bool = False, context: Dict = None, load_only: Union[Sequence[str], Set[str]] = (), dump_only: Union[Sequence[str], Set[str]] = (), partial: Union[bool, Sequence[str], Set[str]] = False, unknown: str = None)[source]

Base class for SQLAlchemy model-based Schemas.

Example:

from marshmallow_sqlalchemy import TableSchema
from mymodels import engine, users

class UserSchema(TableSchema):
    class Meta:
        table = users

schema = UserSchema()

select = users.select().limit(1)
user = engine.execute(select).fetchone()
serialized = schema.dump(user)
OPTIONS_CLASS

alias of TableSchemaOpts

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

Base class for SQLAlchemy model-based Schemas.

Example:

from marshmallow_sqlalchemy import ModelSchema
from mymodels import User, session

class UserSchema(ModelSchema):
    class Meta:
        model = User

schema = UserSchema()

user = schema.load({'name': 'Bill'}, session=session)
existing_user = schema.load({'name': 'Bill'}, instance=User.query.first())
Parameters
  • session – Optional SQLAlchemy session; may be overridden in load.

  • instance – Optional existing instance to modify; may be overridden in load.

OPTIONS_CLASS

alias of ModelSchemaOpts

get_instance(data)[source]

Retrieve an existing record by primary key(s). If the schema instance is transient, return None.

Parameters

data – Serialized data to inform lookup.

load(data, *, session=None, instance=None, transient=False, **kwargs)[source]

Deserialize data to internal representation.

Parameters
  • session – Optional SQLAlchemy session.

  • instance – Optional existing instance to modify.

  • transient – Optional switch to allow transient instantiation.

make_instance(data, **kwargs)[source]

Deserialize data to an instance of the model. 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.

validate(data, *, session=None, **kwargs)[source]

Validate data against the schema, returning a dictionary of validation errors.

Parameters
  • data – The data to validate.

  • many – Whether to validate data as a collection. If None, the value for self.many is used.

  • partial – Whether to ignore missing fields and not require any fields declared. Propagates down to Nested fields as well. If its value is an iterable, only missing fields listed in that iterable will be ignored. Use dot delimiters to specify nested fields.

Returns

A dictionary of validation errors.

New in version 1.1.0.

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

Options class for TableSchema. Adds the following options:

  • table: The SQLAlchemy table to generate the Schema from (required).

  • model_converter: ModelConverter class to use for converting the SQLAlchemy table to

    marshmallow fields.

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

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

Options class for ModelSchema. Adds the following options:

  • model: The SQLAlchemy model to generate the Schema from (required).

  • sqla_session: SQLAlchemy session to be used for deserialization. This is optional; you

    can also pass a session to the Schema’s load method.

  • model_converter: ModelConverter class to use for converting the SQLAlchemy model to

    marshmallow fields.

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

  • transient: Whether load model instances in a transient state (effectively ignoring

    the session).

class marshmallow_sqlalchemy.ModelConverter(schema_cls=None)[source]

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

exception marshmallow_sqlalchemy.ModelConversionError[source]

Raised when an error occurs in converting a SQLAlchemy construct to a marshmallow object.

Fields

class marshmallow_sqlalchemy.fields.Nested(nested: Union[marshmallow.base.SchemaABC, type, str], *, default: Any = <marshmallow.missing>, only: Union[Sequence[str], Set[str]] = None, exclude: Union[Sequence[str], Set[str]] = (), many: bool = False, unknown: str = None, **kwargs)[source]

Nested field that inherits the session from its parent.

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

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

Parameters

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(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 ModelSchema.

Parameters

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(query, value)[source]

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

Parameters
  • query – A SQLAlchemy Query object.

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

Raises

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.

Example:

class TitleCase(Field):
    def _serialize(self, value, attr, obj, **kwargs):
        if not value:
            return ''
        return str(value).title()
Parameters
  • 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.

Returns

The serialized value

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

Return the value for a given key from an object.

Parameters
  • 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.

marshmallow_sqlalchemy.fields.get_primary_keys(model)[source]

Get primary key properties for a SQLAlchemy model.

Parameters

model – SQLAlchemy model class