使用marshal_with无法获取完整对象列表的问题排查
问题排查:获取员工列表接口返回空单条数据的原因
1. 模型表名定义错误
你的Employees类中使用了___tablename___(三个下划线),但SQLAlchemy规定模型的表名属性是__tablename__(双下划线)。这个错误会导致模型无法正确映射到数据库的employees表,执行Employees.query.all()会返回空列表,这是数据为空的根本原因之一。
修正方式:
class Employees(db.Model): __tablename__ = "employees" # 改为双下划线 # ... 其他类属性 ...
2. return_all未正确定义为类方法
return_all函数定义在Employees类外部,且没有添加@classmethod装饰器,但调用时用了Employees.return_all()的类调用方式。这不仅不符合类方法的规范,还可能导致后续代码扩展时出现参数传递错误。
正确做法是将其缩进为类内部方法,并添加@classmethod装饰器:
class Employees(db.Model): __tablename__ = "employees" # ... 其他类属性 ... @classmethod def return_all(cls): def to_json(x): return { 'employee_id': x.emp_no, 'employee_name': f"{x.first_name} {x.last_name}" if x.first_name and x.last_name else None, 'gender': x.gender, 'birth_date': x.birth_date.strftime("%Y-%m-%d") if x.birth_date else None, 'hire_date': x.hire_date.strftime("%Y-%m-%d %H:%M:%S") if x.hire_date else None, 'created_at': x.created_at.strftime("%Y-%m-%d %H:%M:%S") if x.created_at else None, 'last_updated_at': x.last_updated_at.strftime("%Y-%m-%d %H:%M:%S") if x.last_updated_at else None } # 将返回的键改为与序列化结构匹配的'data' return {'data': list(map(lambda x: to_json(x), cls.query.all()))}
3. 序列化结构不匹配
你的return_all最初返回的是键为Employees的字典,但接口中marshal_with使用的GET_EMPLOYEE定义的是键为data的结构。同时,GET_EMPLOYEE中用fields.Nested定义了单个对象,但你需要返回列表,因此需要用fields.List包裹fields.Nested。
修正后的序列化结构:
GET_EMPLOYEE = { 'data': fields.List(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 })) }
4. 日期字段序列化问题
birth_date是Date类型,hire_date、created_at等是DateTime类型,直接返回对象会导致序列化失败或返回异常值,需要先格式化为字符串(上述to_json函数中已添加空值判断和格式化处理)。
经过以上修正后,接口就能正确返回数据库中的员工列表了。
内容的提问来源于stack exchange,提问作者qatesterbecomingprogrammer
相关产品推荐
相关产品推荐

