Registry / serialization / sqlalchemy-serializer

sqlalchemy-serializer

JSON →
library1.6.3pypypi✓ verified 85d ago

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-serializer
INSTALL
IMPORT
SIG · SQLALCHEMY-SERIALI
S
sqlalchemy-serializer
serializationpythonv1.6.3
Install
4.2s avg
Import
686ms
Disk
57MB
Pass rate
10/ 10
Env Coverage10 / 10
glibc
3.93.13
musl
3.93.13
Install & Compatibility
Where this runs
tested against v1.6.3 · pip install
no network on importno background threads
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
py 3.103.910 runs
installs and imports cleanly · install 0.0s · import 0.722s · 57.2MB
glibc
py 3.103.910 runs
installs and imports cleanly · install 4.2s · import 0.650s · 58MB
57MB installed
● package 57MB
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

SerializerMixin
from sqlalchemy_serializer import SerializerMixin

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.

from sqlalchemy import create_engine, Column, Integer, String from sqlalchemy.orm import sessionmaker, declarative_base from sqlalchemy_serializer import SerializerMixin Base = declarative_base() class User(Base, SerializerMixin): __tablename__ = 'users' id = Column(Integer, primary_key=True) name = Column(String) email = Column(String) def __repr__(self): return f"<User(id={self.id}, name='{self.name}')>" engine = create_engine('sqlite:///:memory:') Base.metadata.create_all(engine) Session = sessionmaker(bind=engine) session = Session() user = User(name='Alice', email='alice@example.com') session.add(user) session.commit() # Serialize to dictionary user_dict = user.to_dict() print("Serialized User:", user_dict) # Serialize with specific fields user_name_only = user.to_dict(only=('name',)) print("User name only:", user_name_only) session.close()
Debug
Known issues
gotchaWhen serializing models with circular relationships (e.g., a User has Posts, and a Post references back to a User), `to_dict()` can lead to `RecursionError`. The serializer attempts to infinitely nest related objects.
fix
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.
affects: All versions
gotchaThe `_serializer_exclude_fields` class variable on a model permanently excludes fields from serialization unless explicitly overridden. If you define this on your model, those fields will not appear by default in `to_dict()` output.
fix
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',))`).
affects: All versions
breaking`sqlalchemy-serializer` requires `marshmallow>=3.0.0`. Using older versions of Marshmallow (e.g., 2.x) will lead to import errors or unexpected behavior due to API changes in Marshmallow.
fix
Ensure `marshmallow` is updated to version 3.0.0 or higher by running `pip install marshmallow>=3.0.0` or `pip install --upgrade marshmallow`.
affects: <1.0.0
gotchaWhile `sqlalchemy-serializer` aims to be compatible with SQLAlchemy 2.0, users migrating to SQLAlchemy 2.0 might still encounter issues if their model declarations or session management patterns are not fully updated to SQLAlchemy 2.0's idiomatic style (e.g., using `Mapped` types or `session.scalars()`).
fix
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.
affects: 1.x (when used with SQLAlchemy 2.0)
Errors
Common errors & fixes
AttributeError: 'User' object has no attribute 'to_dict'
Your SQLAlchemy model class does not inherit from `SerializerMixin`.
fix
Ensure your model class inherits from `SerializerMixin`: `class MyModel(Base, SerializerMixin):`
ModuleNotFoundError: No module named 'sqlalchemy_serializer'
The `sqlalchemy-serializer` library is not installed, or you have a typo in the import statement.
fix
Install the library: `pip install sqlalchemy-serializer`. Then ensure the import is correct: `from sqlalchemy_serializer import SerializerMixin`.
RecursionError: maximum recursion depth exceeded while calling a Python object
You are trying to serialize models with circular relationships (e.g., parent-child where child also references parent) without limiting the nesting depth.
fix
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.
TypeError: Object of type <class 'uuid.UUID'> is not JSON serializable
You have a field in your model with a custom Python type (like `UUID`, `datetime` in some contexts, custom enums, etc.) that the default JSON serializer doesn't know how to convert.
fix
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()`.
Upgrade
Version history
1.6.3latest on PyPI · released Apr 18, 2026
Audit
Dependencies
SQLAlchemyrequiredCore ORM functionality for database interaction and model definition.
marshmallowrequiredUsed for data validation and more complex serialization/deserialization schemas.
Agent activity
19 hits · last 30 days
node
12
Meta
2
OpenAI (training)
2
Resources
sqlalchemy-serializer — pip install sqlalchemy-serializer · libregistry