Skip to main content

SQLAlchemy integration with the marshmallow (de)serialization library

Project description

Latest version Build status Documentation marshmallow 3|4 compatible

Homepage: https://marshmallow-sqlalchemy.readthedocs.io/

SQLAlchemy integration with the marshmallow (de)serialization library.

Declare your models

import sqlalchemy as sa
from sqlalchemy.orm import (
    DeclarativeBase,
    backref,
    relationship,
    scoped_session,
    sessionmaker,
)

from marshmallow_sqlalchemy import SQLAlchemySchema, auto_field

engine = sa.create_engine("sqlite:///:memory:")
session = scoped_session(sessionmaker(bind=engine))


class Base(DeclarativeBase):
    pass


class Author(Base):
    __tablename__ = "authors"
    id = sa.Column(sa.Integer, primary_key=True)
    name = sa.Column(sa.String, nullable=False)

    def __repr__(self):
        return "<Author(name={self.name!r})>".format(self=self)


class Book(Base):
    __tablename__ = "books"
    id = sa.Column(sa.Integer, primary_key=True)
    title = sa.Column(sa.String)
    author_id = sa.Column(sa.Integer, sa.ForeignKey("authors.id"))
    author = relationship("Author", backref=backref("books"))


Base.metadata.create_all(engine)

Generate marshmallow schemas

from marshmallow_sqlalchemy import SQLAlchemySchema, auto_field


class AuthorSchema(SQLAlchemySchema):
    class Meta:
        model = Author
        load_instance = True  # Optional: deserialize to model instances

    id = auto_field()
    name = auto_field()
    books = auto_field()


class BookSchema(SQLAlchemySchema):
    class Meta:
        model = Book
        load_instance = True

    id = auto_field()
    title = auto_field()
    author_id = auto_field()

You can automatically generate fields for a model’s columns using SQLAlchemyAutoSchema. The following schema classes are equivalent to the above.

from marshmallow_sqlalchemy import SQLAlchemyAutoSchema


class AuthorSchema(SQLAlchemyAutoSchema):
    class Meta:
        model = Author
        include_relationships = True
        load_instance = True


class BookSchema(SQLAlchemyAutoSchema):
    class Meta:
        model = Book
        include_fk = True
        load_instance = True

Make sure to declare Models before instantiating Schemas. Otherwise sqlalchemy.orm.configure_mappers() will run too soon and fail.

(De)serialize your data

author = Author(name="Chuck Paluhniuk")
author_schema = AuthorSchema()
book = Book(title="Fight Club", author=author)
session.add(author)
session.add(book)
session.commit()

dump_data = author_schema.dump(author)
print(dump_data)
# {'id': 1, 'name': 'Chuck Paluhniuk', 'books': [1]}

load_data = author_schema.load(dump_data, session=session)
print(load_data)
# <Author(name='Chuck Paluhniuk')>

Get it now

pip install -U marshmallow-sqlalchemy

Requires Python >= 3.9, marshmallow >= 3.18.0, and SQLAlchemy >= 1.4.40.

Documentation

Documentation is available at https://marshmallow-sqlalchemy.readthedocs.io/ .

License

MIT licensed. See the bundled LICENSE file for more details.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

marshmallow_sqlalchemy-1.2.0.tar.gz (50.8 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

marshmallow_sqlalchemy-1.2.0-py3-none-any.whl (15.6 kB view details)

Uploaded Python 3

File details

Details for the file marshmallow_sqlalchemy-1.2.0.tar.gz.

File metadata

  • Download URL: marshmallow_sqlalchemy-1.2.0.tar.gz
  • Upload date:
  • Size: 50.8 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.0.1 CPython/3.12.8

File hashes

Hashes for marshmallow_sqlalchemy-1.2.0.tar.gz
Algorithm Hash digest
SHA256 9787e95d52dc39f351db1ca47a7ca30b593e4f02b5c54592680bc03ce8ce0e79
MD5 da3500ba7a5c4eb499c3564748d76ccf
BLAKE2b-256 9fa75ee9c0073c34a2141d4ae5e90a6c131bc859c6f7b3367ba55c6910d48f3b

See more details on using hashes here.

Provenance

The following attestation bundles were made for marshmallow_sqlalchemy-1.2.0.tar.gz:

Publisher: build-release.yml on marshmallow-code/marshmallow-sqlalchemy

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file marshmallow_sqlalchemy-1.2.0-py3-none-any.whl.

File metadata

File hashes

Hashes for marshmallow_sqlalchemy-1.2.0-py3-none-any.whl
Algorithm Hash digest
SHA256 e1d97ab55103683a9f737a99f6d7eea286135c1eb23ba7d865fa3bc05358f530
MD5 5726a84feede33ecd353c4bf4adb0301
BLAKE2b-256 4d42f6ce390cdbe4d2f3d03101e7cb8fceaea5ae1347e41654ffa0d8c6751b2d

See more details on using hashes here.

Provenance

The following attestation bundles were made for marshmallow_sqlalchemy-1.2.0-py3-none-any.whl:

Publisher: build-release.yml on marshmallow-code/marshmallow-sqlalchemy

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page