SQLAlchemy自引用多对多关联添加预测时非空约束报错问题
问题解答
首先明确:完全可以同时存储这两个预测,不需要先提交底层预测。你遇到的错误和提交顺序无关,核心问题是你尝试保存的某个Prediction对象没有设置location_id(或者说没有关联有效的Location实例),违反了该字段的非空约束。
你的Prediction模型里location_id是必填项(没有设置nullable=True),不管是底层预测还是依赖预测,只要是Prediction实例,都必须关联一个Location。
正确的操作方式是:
- 先创建并关联一个
Location实例给所有需要保存的Prediction - 建立两个
Prediction之间的依赖关系 - 把所有相关对象(Location、两个Prediction)添加到会话后,一次性提交
举个具体的代码例子:
# 创建Location实例 location = Location() session.add(location) # 创建两个Prediction,都绑定同一个Location underlying_pred = Prediction(location=location) dependant_pred = Prediction(location=location) # 设置依赖关系 dependant_pred.underlying_predictions.append(underlying_pred) # 将两个预测加入会话 session.add(underlying_pred) session.add(dependant_pred) # 一次性提交所有变更 session.commit()
SQLAlchemy会自动处理插入顺序:先插入Location,再插入两个Prediction,最后插入关联表prediction_relations的记录,全程不需要拆分提交步骤。
如果还是报错,检查一下是不是某个Prediction实例漏了关联Location——哪怕单独保存一个没有location_id的Prediction,也会触发同样的非空约束错误。
内容的提问来源于stack exchange,提问作者Steffen
相关产品推荐
相关产品推荐

