{"id":10257,"library":"sqlalchemy-serializer","title":"SQLAlchemy Serializer","description":"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.","status":"active","version":"1.6.2","language":"en","source_language":"en","source_url":"https://github.com/n0nSmth/sqlalchemy-serializer","tags":["sqlalchemy","serialization","orm","json","api","marshmallow"],"install":[{"cmd":"pip install sqlalchemy-serializer","lang":"bash","label":"Install latest version"}],"dependencies":[{"reason":"Core ORM functionality for database interaction and model definition.","package":"SQLAlchemy","optional":false},{"reason":"Used for data validation and more complex serialization/deserialization schemas.","package":"marshmallow","optional":false}],"imports":[{"symbol":"SerializerMixin","correct":"from sqlalchemy_serializer import SerializerMixin"}],"quickstart":{"code":"from sqlalchemy import create_engine, Column, Integer, String\nfrom sqlalchemy.orm import sessionmaker, declarative_base\nfrom sqlalchemy_serializer import SerializerMixin\n\nBase = declarative_base()\n\nclass User(Base, SerializerMixin):\n    __tablename__ = 'users'\n    id = Column(Integer, primary_key=True)\n    name = Column(String)\n    email = Column(String)\n\n    def __repr__(self):\n        return f\"<User(id={self.id}, name='{self.name}')>\"\n\nengine = create_engine('sqlite:///:memory:')\nBase.metadata.create_all(engine)\nSession = sessionmaker(bind=engine)\nsession = Session()\n\nuser = User(name='Alice', email='alice@example.com')\nsession.add(user)\nsession.commit()\n\n# Serialize to dictionary\nuser_dict = user.to_dict()\nprint(\"Serialized User:\", user_dict)\n\n# Serialize with specific fields\nuser_name_only = user.to_dict(only=('name',))\nprint(\"User name only:\", user_name_only)\n\nsession.close()","lang":"python","description":"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."},"warnings":[{"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.","message":"When 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.","severity":"gotcha","affected_versions":"All versions"},{"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',))`).","message":"The `_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.","severity":"gotcha","affected_versions":"All versions"},{"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`.","message":"`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.","severity":"breaking","affected_versions":"<1.0.0"},{"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.","message":"While `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()`).","severity":"gotcha","affected_versions":"1.x (when used with SQLAlchemy 2.0)"}],"env_vars":null,"last_verified":"2026-04-17T00:00:00.000Z","next_check":"2026-07-16T00:00:00.000Z","problems":[{"fix":"Ensure your model class inherits from `SerializerMixin`: `class MyModel(Base, SerializerMixin):`","cause":"Your SQLAlchemy model class does not inherit from `SerializerMixin`.","error":"AttributeError: 'User' object has no attribute 'to_dict'"},{"fix":"Install the library: `pip install sqlalchemy-serializer`. Then ensure the import is correct: `from sqlalchemy_serializer import SerializerMixin`.","cause":"The `sqlalchemy-serializer` library is not installed, or you have a typo in the import statement.","error":"ModuleNotFoundError: No module named 'sqlalchemy_serializer'"},{"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.","cause":"You are trying to serialize models with circular relationships (e.g., parent-child where child also references parent) without limiting the nesting depth.","error":"RecursionError: maximum recursion depth exceeded while calling a Python object"},{"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()`.","cause":"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.","error":"TypeError: Object of type <class 'uuid.UUID'> is not JSON serializable"}]}