当我尝试更新数据时,我的SQLAlchemy模型遇到了一些奇怪的行为。我有一个这样定义的一对多关系:
app = Flask(__name__)
app.config[
"SQLALCHEMY_DATABASE_URI"
] = "postgresql://geonatadmin:monpassachanger@localhost:5432/geonature2db_test"
app.debug = True
DB = SQLAlchemy(app)
class Child(DB.Model):
__tablename__ = "Child"
id_child = DB.Column(DB.Integer, primary_key=True)
id_parent = DB.Column(DB.Integer, ForeignKey("Parent.id_parent"))
name = DB.Column(DB.Unicode(50))
class Parent(DB.Model):
__tablename__ = "Parent"
id_parent = DB.Column(DB.Integer, primary_key=True)
name = DB.Column(DB.Unicode(50))
childrens = relationship("Child", lazy="joined", cascade="all, delete-orphan")
DB.create_all()
我正在尝试从我的API发送的JSON更新Parent
和Child
。在我的示例中,一位父母已经有一个孩子,我尝试为其添加两个新孩子:
with app.app_context():
first_json = {"name": "parent1", "childrens": [{"name": "john"}]}
childrens = first_json.pop("childrens")
parent = Parent(**first_json)
for child in childrens:
parent.childrens.append(Child(**child))
DB.session.add(parent)
DB.session.commit()
DB.session.flush()
second_json = {
"id_parent": 1,
"name": "parent1",
"childrens": [
{"id_child": 1, "name": "john"},
{"id_child": None, "name": "foo"},
{"id_child": None, "name": "bar"},
],
}
childrens = second_json.pop("childrens")
parent = Parent(**second_json)
for child in childrens:
parent.childrens.append(Child(**child))
DB.session.merge(parent)
DB.session.commit()
最后,我的数据库中只有孩子1和孩子3。永远不会添加孩子2。
我试图获取有关此配置发出的实际SQL的更多信息:
current_app.config["SQLALCHEMY_ECHO"] = True
并且确实没有针对Child 2的INSERT语句。
答案 0 :(得分:1)
我最终发现,如果删除“ id_child”为“无”,则合并工作正常。 像这样:
second_json = {
"id_parent": 1,
"name": "parent1",
"childrens": [
{"id_child": 1, "name": "john"},
{"name": "foo"},
{"name": "bar"},
],
}