marshmallow-sqlalchemy provides integration between the SQLAlchemy ORM and the marshmallow (de)serialization library. It simplifies creating schemas for SQLAlchemy models, enabling automatic field generation and handling of relationships. The current version is 1.5.0, and it follows a release cadence generally aligned with its core dependencies, marshmallow and SQLAlchemy, with major updates addressing compatibility and new features.
pip install marshmallow-sqlalchemyVerified import paths — ran on the pinned version, not inferred.
This quickstart demonstrates how to define a SQLAlchemy model, create a corresponding `SQLAlchemyAutoSchema`, and then use it to serialize (dump) and deserialize (load) data, including creating new instances and updating existing ones. It highlights the importance of passing the `session` to the schema for full functionality, especially with relationships.
Instead of `UserSchema(load_instance=True).load(data)`, use `user_schema.load(data, instance=existing_object)`. For creating new instances, simply `user_schema.load(data)`.
Pass `session=your_sqlalchemy_session` to the schema constructor (e.g., `UserSchema(session=session)`) or define `Meta.sqla_session = your_sqlalchemy_session` within your schema's `Meta` class.
For serialization, ensure your SQLAlchemy query uses eager loading (e.g., `session.query(Parent).options(joinedload(Parent.children))`) before passing objects to the schema. For deserialization, ensure your nested schema correctly handles the relationship (e.g., by setting `partial=True` if necessary for updates).
Define custom fields directly as class attributes in your `SQLAlchemyAutoSchema` subclass (e.g., `my_field = fields.String(data_key='custom_name')`) rather than inside the `Meta` class.
For partial updates, pass `partial=True` to the `load` method (e.g., `user_schema.load(data, instance=existing_object, partial=True)`). This tells the schema to ignore missing required fields not present in the input data.
For partial updates, ensure you pass `partial=True` to the `load` method (e.g., `user_schema.load(update_data, instance=alice, partial=True)`). If a field should always be optional during updates, consider setting `required=False` in your schema field definition.
Ensure your virtual environment is activated and install the package using `pip install marshmallow-sqlalchemy`.
Ensure your SQLAlchemy model is correctly defined using SQLAlchemy's declarative base, and that you are passing a mapped model class (not an instance) to the schema's `Meta.model` attribute.
Pass an active SQLAlchemy session to your schema instance: `MySchema(session=db.session)` (assuming `db.session` is your SQLAlchemy session object).
Verify that 'some_column' exactly matches a column or relationship name defined in your `SomeModel` SQLAlchemy class. Check for typos or ensure the column is indeed part of the model.