pythonflaskflask-sqlalchemyflask-restful

Unable to get whole list of objects using marshal_with


I am trying to get list of all objects from database, for which I am using following logic to get all results within Employees model page:

class Employees(db.Model):
    ___tablename___ = "employees"

    emp_no = db.Column(db.Integer, primary_key=True)
    birth_date = db.Column(db.Date)
    first_name = db.Column(db.String())
    last_name = db.Column(db.String())
    gender = db.Column(db.Enum(GenderChoices, values_callable=lambda x: [str(member.value)
                                                                         for member in GenderChoices]))

    hire_date = db.Column(db.DateTime)
    created_at = db.Column(db.DateTime, default=datetime.datetime.utcnow)
    last_updated_at = db.Column(db.DateTime, default=datetime.datetime.utcnow)

def return_all(cls):
    def to_json(x):
        return {
            'employee_id': x.emp_no,
            'employee_name': x.first_name + " " + x.last_name,
            'gender': x.gender,
            'birth_date': x.birth_date,
            'hire_date': x.hire_date,
            'created_at': x.created_at.strftime("%Y-%m-%d %H:%M:%S"),
            'last_updated_at': x.last_updated_at.strftime("%Y-%m-%d %H:%M:%S")
        }
    return {'Employees': list(map(lambda x: to_json(x), Employees.query.all()))}

for end point logic, I am using following logic:

GET_EMPLOYEE = {
        'data': fields.Nested({
            'employee_id': fields.Integer,
            'employee_name': fields.String,
            'gender': fields.String,
            'birth_date': fields.String,
            'hire_date': fields.String,
            'created_at': fields.Raw,
            'last_updated_at': fields.Raw
        })
    }

class GetAllEmployees(Resource):
    @marshal_with(GET_EMPLOYEE)
    def get(self):
        return Employees.return_all()

Upon hitting on end point, I am not getting a list, but a single response of null values, like this:

{
    "data": {
        "employee_id": 0,
        "employee_name": null,
        "gender": null,
        "birth_date": null,
        "hire_date": null,
        "created_at": null,
        "last_updated_at": null
    }
}

What possibly can be a problem?


Solution

  • Ok, after a while, I saw that I have to change my marshal_with fields, so I made some changes as per that..

    GET_ALL_EMPLOYEE = {
            'Employees': fields.Nested({
                'employee_id': fields.Integer,
                'employee_name': fields.String,
                'gender': fields.String,
                'birth_date': fields.String,
                'hire_date': fields.String,
                'created_at': fields.Raw,
                'last_updated_at': fields.Raw
            })
        }
    

    and It worked accordingly.