Search code examples
pythonsqlalchemyflask-sqlalchemymarshmallow

UserSchema class object returns empty dict


I have data in my sqlite db, but when I use UserSchema object I get an empty dict.

ma = Marshmallow()
# User Schema
class UserSchema(ma.Schema):

    class Meta:
        fields = (
            "id",
            "fname", 
            "mname", 
            "lname", 
            "dob", 
            "user_type", 
            "email", 
            "mobile_phone", 
            "landline_phone",
            "place_of_birth", 
            "government_id", 
            "government_id_number",
            "registered",
            "modified"
            )

# Init Schema 
user_schema = UserSchema()

but when I use it with get endpoint.

@api_blueprint.route("/api/users", methods=["GET"])
def get_users():
    all_users = User.query.all()
    result = user_schema.dump(all_users)
    return jsonify(result)

result is always coming out to be None.


Solution

  • You have to pass many=True to dump method if you want to serialize multiple objects.

    result = user_schema.dump(all_users, many=True)