pythonflasksqlalchemymarshmallow-sqlalchemy

Marshmallow-sqlalchemy: How to load all fields into schema from model which loads fields from database directly?


I have this schema:

class Users(SQLAlchemyAutoSchema):
    class Meta:
        model = models.Users
        include_fk = True
        include_relationships = True

The model is:

class Users(db.Model):
    __table__ = db.Model.metadata.tables['dbo.Users']

As you can see, columns are set directly from table, and if I print columns from model, all columns are loaded, but if i print the schema, it is just an empty dict. I don't know how to load all fields without set them manually.

According to marshmallow-sqlalchemy documentation:

Any column_property on the model that does not derive directly from Column (such as a mapped expression), will be detected and marked as dump_only. Hybrid_property is not automatically handled at all, and would need to be explicitly declared as a field.

But I don't know what it means exactly. I tried using fields = '__all__' but it throws the error: ValueError: fields option must be a list or tuple.


Solution

  • The solution was set fields from model's columns:

    class Users(ma.SQLAlchemyAutoSchema):
        class Meta:
            model = models.Users
            include_fk = True
            fields = models.Users.__table__.columns.keys() # This is the solution