Flask+SQLAlchemy中无法访问查询过滤结果的问题求助
Flask+SQLAlchemy中无法访问查询过滤结果的问题求助
嘿,我仔细瞅了你的代码,问题其实挺明显的——你的find_by_purpose_and_id类方法返回的不是实际查询到的数据库记录,而是一个SQLAlchemy Query对象,这就是你没法直接访问结果属性、也没法正常返回给前端的核心原因!
问题根源
你看这段类方法代码:
@classmethod def find_by_purpose_and_id(cls, client_id, purpose): return cls.query.filter_by(client_id= client_id,purpose=purpose)
cls.query.filter_by(...)只是帮你构建了一条查询语句,并没有实际去数据库执行查询捞数据。这个Query对象必须调用.all()或者.first()这类方法,才能拿到真正的记录数据。
解决方案
根据你的业务需求,分两种情况修改代码:
情况1:需要返回所有匹配的记录(多条)
修改类方法,加上.all()来获取所有符合条件的记录列表:
@classmethod def find_by_purpose_and_id(cls, client_id, purpose): # 返回所有符合条件的记录列表,无匹配则返回空列表 return cls.query.filter_by(client_id=client_id, purpose=purpose).all()
同时要调整put方法的响应Schema配置,因为返回的是列表,需要加上many=True:
@blp.response(200, ConfigSchema(many=True)) # 新增many=True适配列表返回 def put(self, request_data, client_id): configs = ConfigsModel.find_by_purpose_and_id(12, 'INITIAL') if not configs: abort(404, message="Missing Configuration for client") # 现在configs是列表,可以正常遍历访问属性 for config in configs: print(config.endpoint) print(configs) return configs
情况2:只需要返回第一条匹配的记录(单条)
如果你的业务逻辑里client_id+purpose是唯一组合,那用.first()更合适:
@classmethod def find_by_purpose_and_id(cls, client_id, purpose): # 返回第一条符合条件的记录,无匹配则返回None return cls.query.filter_by(client_id=client_id, purpose=purpose).first()
这时候put方法里的遍历代码要去掉(因为返回的是单个对象,不是列表),Schema也不用加many=True:
@blp.response(200, ConfigSchema) def put(self, request_data, client_id): config = ConfigsModel.find_by_purpose_and_id(12, 'INITIAL') if not config: abort(404, message="Missing Configuration for client") # 直接访问单个对象的属性 print(config.endpoint) print(config) return config
小提醒
记得确认你的数据库里确实存在client_id=12且purpose='INITIAL'的记录,不然还是会触发404错误哦~
备注:内容来源于stack exchange,提问作者Rual
相关产品推荐
相关产品推荐

