SQLAlchemy Serializer (sqlalchemy-serializer) is a mixin for SQLAlchemy models that simplifies their serialization into dictionaries or JSON, often used in API contexts. It handles relationships, allows field exclusion/inclusion, and supports nested serialization. The current version is 1.6.2, and it typically sees regular maintenance releases.
pip install sqlalchemy-serializerVerified import paths — ran on the pinned version, not inferred.
This quickstart demonstrates how to apply `SerializerMixin` to an SQLAlchemy model and use its `to_dict()` method for basic serialization. It sets up an in-memory SQLite database, creates a simple User model, adds a user, and then serializes it, showing how to include only specific fields.
Use the `max_nesting` parameter in `to_dict()` to limit recursion depth (e.g., `user.to_dict(max_nesting=1)`). Alternatively, explicitly exclude the problematic relationship fields using `exclude` in `to_dict()` or `_serializer_exclude_fields` on the model class.
Be mindful when defining `_serializer_exclude_fields`. To include an excluded field for a specific call, you must explicitly pass it in the `include` parameter of `to_dict()` (e.g., `obj.to_dict(include=('secret_field',))`).Ensure `marshmallow` is updated to version 3.0.0 or higher by running `pip install marshmallow>=3.0.0` or `pip install --upgrade marshmallow`.
Ensure your SQLAlchemy model declarations and session usage fully conform to SQLAlchemy 2.0 best practices. Although the `SerializerMixin` itself is designed for compatibility, underlying ORM issues can surface when trying to serialize.
Ensure your model class inherits from `SerializerMixin`: `class MyModel(Base, SerializerMixin):`
Install the library: `pip install sqlalchemy-serializer`. Then ensure the import is correct: `from sqlalchemy_serializer import SerializerMixin`.
When calling `to_dict()`, specify `max_nesting` (e.g., `obj.to_dict(max_nesting=1)`), or use `exclude` to prevent the problematic relationship field from being serialized. You can also define `_serializer_exclude_fields` on your model for permanent exclusion.
For `datetime` objects, `sqlalchemy-serializer` usually handles them. For other custom types, you might need to convert them to a serializable format (like `str`) before calling `to_dict()`, or extend `serializer_args` on the `SerializerMixin` to provide custom encoders if you're directly converting to JSON using `json.dumps` after `to_dict()`.