marshmallow-sqlalchemy icon indicating copy to clipboard operation
marshmallow-sqlalchemy copied to clipboard

Preserve Excluded Keys (#132) breaks Marshmallow 2.x

Open hstehling opened this issue 7 years ago • 2 comments

When calling schema.__filter_fields with a collection, marshmallow tries to use the first item as a prototype to figure out the fields.

In case of an empty collection, there is an important difference between marshmallow 2 and marshmallow 3:

Marshmallow 3 returns {k: v for k, v in self.declared_fields.items() if k in field_names} while marshmallow 2 simply returns self.declared_fields (including excluded fields which will be filtered out later).

In marshmallow-sqlalchemy, #132 adds excluded keys with a value of None instead of simply skipping them. This leads to a crash in marshmallow 2, because None is used as field_obj in schema.__set_field_attrs.

So, marshmallow-sqlalchemy 0.14.1 is currently broken for marshmallow 2.

hstehling avatar Sep 09 '18 22:09 hstehling

Thanks @hstehling for investigating and reporting this. I'd certainly review and merge a PR =)

sloria avatar Sep 10 '18 13:09 sloria

Experiencing the same issue

Model:


class Article(db.Model):
    id = Column(Integer, primary_key=True)
    user_id = Column(ForeignKey("user.id"))
    org_id = Column(ForeignKey("organization.id"))
    title = Column(UnicodeText(), nullable=False)
    image = Column(String(255), nullable=False)
    content = Column(UnicodeText())
    drafted = Column(Boolean)
    categories = relationship("Category")
    comments = relationship("Comment")
    total_visited = Column(Integer)

Schema:


class CreateArticleSchema(ma.SQLAlchemyAutoSchema):
    class Meta:
        model = Article
        exclude = ("id", "user_id")
        fields = ("org_id", "title", "image", "content", "drafted", "categories")

    categories = fields.List(fields.String())

Output:

ValueError: Invalid fields for <CreateArticleSchema(many=False)>: {'id', 'user_id'}.

aprilahijriyan avatar Jan 07 '21 00:01 aprilahijriyan