0

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
    }
}
koopmac
  • 936
  • 10
  • 27
  • Hard to guess without seeing what `Filter` and `FilterSchema` look like. Does `dump` in `FilterSchema` return an object with a `data` property? Also, when you say it works when using `query.first()`, do you mean you merely replace the `filters = Filter.query.all()` line or something else? – Zunino Mar 25 '20 at 23:40
  • `FilterSchema` is just a marshmallow schema that displays the id of the returned rows: `class FilterSchema(ma.Schema): id = fields.Integer()`. Yes, I mean replacing `Filter.query.all()` with `Filter.query.first()`, I'll edit the question to clarify. – koopmac Mar 26 '20 at 04:03

1 Answers1

2

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.

koopmac
  • 936
  • 10
  • 27