1**********************
2marshmallow-sqlalchemy
3**********************
4
5|pypi-package| |build-status| |docs| |marshmallow3| |black|
6
7Homepage: https://marshmallow-sqlalchemy.readthedocs.io/
8
9`SQLAlchemy <http://www.sqlalchemy.org/>`_ integration with the  `marshmallow <https://marshmallow.readthedocs.io/en/latest/>`_ (de)serialization library.
10
11Declare your models
12===================
13
14.. code-block:: python
15
16    import sqlalchemy as sa
17    from sqlalchemy.ext.declarative import declarative_base
18    from sqlalchemy.orm import scoped_session, sessionmaker, relationship, backref
19
20    engine = sa.create_engine("sqlite:///:memory:")
21    session = scoped_session(sessionmaker(bind=engine))
22    Base = declarative_base()
23
24
25    class Author(Base):
26        __tablename__ = "authors"
27        id = sa.Column(sa.Integer, primary_key=True)
28        name = sa.Column(sa.String, nullable=False)
29
30        def __repr__(self):
31            return "<Author(name={self.name!r})>".format(self=self)
32
33
34    class Book(Base):
35        __tablename__ = "books"
36        id = sa.Column(sa.Integer, primary_key=True)
37        title = sa.Column(sa.String)
38        author_id = sa.Column(sa.Integer, sa.ForeignKey("authors.id"))
39        author = relationship("Author", backref=backref("books"))
40
41
42    Base.metadata.create_all(engine)
43
44Generate marshmallow schemas
45============================
46
47.. code-block:: python
48
49    from marshmallow_sqlalchemy import SQLAlchemySchema, auto_field
50
51
52    class AuthorSchema(SQLAlchemySchema):
53        class Meta:
54            model = Author
55            load_instance = True  # Optional: deserialize to model instances
56
57        id = auto_field()
58        name = auto_field()
59        books = auto_field()
60
61
62    class BookSchema(SQLAlchemySchema):
63        class Meta:
64            model = Book
65            load_instance = True
66
67        id = auto_field()
68        title = auto_field()
69        author_id = auto_field()
70
71You can automatically generate fields for a model's columns using `SQLAlchemyAutoSchema`.
72The following schema classes are equivalent to the above.
73
74.. code-block:: python
75
76    from marshmallow_sqlalchemy import SQLAlchemyAutoSchema
77
78
79    class AuthorSchema(SQLAlchemyAutoSchema):
80        class Meta:
81            model = Author
82            include_relationships = True
83            load_instance = True
84
85
86    class BookSchema(SQLAlchemyAutoSchema):
87        class Meta:
88            model = Book
89            include_fk = True
90            load_instance = True
91
92
93Make sure to declare `Models` before instantiating `Schemas`. Otherwise `sqlalchemy.orm.configure_mappers() <https://docs.sqlalchemy.org/en/latest/orm/mapping_api.html>`_ will run too soon and fail.
94
95(De)serialize your data
96=======================
97
98.. code-block:: python
99
100    author = Author(name="Chuck Paluhniuk")
101    author_schema = AuthorSchema()
102    book = Book(title="Fight Club", author=author)
103    session.add(author)
104    session.add(book)
105    session.commit()
106
107    dump_data = author_schema.dump(author)
108    print(dump_data)
109    # {'id': 1, 'name': 'Chuck Paluhniuk', 'books': [1]}
110
111    load_data = author_schema.load(dump_data, session=session)
112    print(load_data)
113    # <Author(name='Chuck Paluhniuk')>
114
115Get it now
116==========
117::
118
119   pip install -U marshmallow-sqlalchemy
120
121
122Requires Python >= 3.6, marshmallow >= 3.0.0, and SQLAlchemy >= 1.2.0.
123
124Documentation
125=============
126
127Documentation is available at https://marshmallow-sqlalchemy.readthedocs.io/ .
128
129Project Links
130=============
131
132- Docs: https://marshmallow-sqlalchemy.readthedocs.io/
133- Changelog: https://marshmallow-sqlalchemy.readthedocs.io/en/latest/changelog.html
134- Contributing Guidelines: https://marshmallow-sqlalchemy.readthedocs.io/en/latest/contributing.html
135- PyPI: https://pypi.python.org/pypi/marshmallow-sqlalchemy
136- Issues: https://github.com/marshmallow-code/marshmallow-sqlalchemy/issues
137
138License
139=======
140
141MIT licensed. See the bundled `LICENSE <https://github.com/marshmallow-code/marshmallow-sqlalchemy/blob/dev/LICENSE>`_ file for more details.
142
143
144.. |pypi-package| image:: https://badgen.net/pypi/v/marshmallow-sqlalchemy
145    :target: https://pypi.org/project/marshmallow-sqlalchemy/
146    :alt: Latest version
147.. |build-status| image:: https://dev.azure.com/sloria/sloria/_apis/build/status/marshmallow-code.marshmallow-sqlalchemy?branchName=dev
148    :target: https://dev.azure.com/sloria/sloria/_build/latest?definitionId=10&branchName=dev
149    :alt: Build status
150.. |docs| image:: https://readthedocs.org/projects/marshmallow-sqlalchemy/badge/
151   :target: http://marshmallow-sqlalchemy.readthedocs.io/
152   :alt: Documentation
153.. |marshmallow3| image:: https://badgen.net/badge/marshmallow/3
154    :target: https://marshmallow.readthedocs.io/en/latest/upgrading.html
155    :alt: marshmallow 3 compatible
156.. |black| image:: https://badgen.net/badge/code%20style/black/000
157    :target: https://github.com/ambv/black
158    :alt: code style: black
159