question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Autogenerating Nested fields by SQLAlchemyAutoSchema

See original GitHub issue

Hi, I’m looking through the new SQLAlchemyAutoSchema and I’m failing to find a way to autogenerate Nested fields based on relationship. Even with include_relationships = True the generated fields appear to be fields.Related, not fields.Nested as I would have guessed. The autogenerating schemas will certainly cleanup my code quite a lot and having the option to generate Nested fields directly would be nice to have. Is such a feature considered? Or is it already included and I’m missing something?

Here’s a a fully runnable example showing the different behavior between schema generated by SQLAlchemyAutoSchema and one with manually added field author = fields.Nested(AuthorSchema). I’m primarily looking for the output of the nested version.

from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker, relationship, joinedload
from sqlalchemy import Column, Integer, String, ForeignKey
from marshmallow_sqlalchemy import SQLAlchemyAutoSchema, auto_field, fields

engine = create_engine('sqlite:///test5.db', echo=False)
Session = sessionmaker(bind=engine)
session = Session()

Base = declarative_base()

class Author(Base):
    __tablename__ = 'authors'
    id = Column(Integer, primary_key=True)
    name = Column(String(255))

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

Base.metadata.create_all(engine)

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

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

class BookSchemaWithNested(SQLAlchemyAutoSchema):
    class Meta:
        model = Book
        load_instance = True
        include_relationships = True

    author = fields.Nested(AuthorSchema)

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

print(AuthorSchema().dump(author)) # {'books': [1], 'name': 'Chuck Paluhniuk', 'id': 1}
print(BookSchema().dump(book)) # {'id': 1, 'title': 'Fight Club', 'author': 1}
print(BookSchemaWithNested().dump(book)) # {'id': 1, 'title': 'Fight Club', 'author': {'books': [1], 'name': 'Chuck Paluhniuk', 'id': 1}}

book = session.query(Book).options(joinedload("author")).get(1)
print(BookSchema().dump(book)) # {'id': 1, 'title': 'Fight Club', 'author': 1}

print(BookSchema._declared_fields["author"]) # <fields.Related(default=<marshmallow.missing>, ...
print(BookSchemaWithNested._declared_fields["author"]) # <fields.Nested(default=<marshmallow.missing>, ...

Issue Analytics

  • State:closed
  • Created 4 years ago
  • Comments:5 (2 by maintainers)

github_iconTop GitHub Comments

1reaction
rchukkayapallycommented, Feb 21, 2022

mato2000 How did you solve this problem?

0reactions
mato2000commented, Dec 2, 2021

Thanks for the reply! I was trying this example but it was slightly different and didn’t work. Fixed and now works. Thanks and sorry for bothering!

Read more comments on GitHub >

github_iconTop Results From Across the Web

flask sqlalchemy - Nested fields with mashmallow_sqlalchemy ...
I have tried adding part_numbers = ma.Nested(PartNumbers) to the Machine schema inside models.py , but it didn't change the result! my_app ...
Read more >
API Reference - marshmallow-sqlalchemy
Mark a field to autogenerate from a model or table. Parameters: column_name – Name of the column to generate the field from. If...
Read more >
marshmallow-sqlalchemy - Read the Docs
You can automatically generate fields for a model's columns using SQLAlchemyAutoSchema. The following schema classes are equivalent to the above ...
Read more >
marshmallow - Bountysource
fields.Nested should optionally pass the parent object to the Nested Schema $ ... relationship from marshmallow_sqlalchemy import SQLAlchemyAutoSchema from ...
Read more >
marshmallow-sqlalchemy Changelog - pyup.io
from marshmallow_sqlalchemy import SQLAlchemyAutoSchema from . import models ... Nested`` field that inherits its session from its schema.
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found