Search code examples
pythonflaskmarshmallowflask-marshmallow

Why does Marshmallow return empty for multiple items but returns a single item?


I'm building an API using Flask and marshmallow to format the query results but for some reason Filter.query.all() is returning empty, but when I replace that with Filter.query.first() it returns the first filter. I've also double checked my database to make sure multiple entries are there. Is there anything I'm doing wrong here?

from Model import db, Filter

class FilterSchema(ma.Schema):
    id = fields.Integer()

filter_schema = FilterSchema()

### returns list of all filters in Filter db

def get(self):
    filters = Filter.query.all()
    filters = filter_schema.dump(filters).data
    return {'status': 'success', 'data': filters}, 200

returns:

{
    "status": "success",
    "data": {}
}

while Filter.query.first() returns:

{
    "status": "success",
    "data": {
        "id": 1
    }
}

Solution

  • It turns out for a schema in marshmallow you need to specify whether the schema is dumping multiple entries or not. When there is more than one, add many=True to your FilterSchema():

    ie: filter_schema = FilterSchema(many=True)

    or even better, add a different variable called filters_schema = FilterSchema(many=True)

    and choose which one to use depending on the data you want returned.