Python 与包含的相关对象合并时,不会保留新关系

Python 与包含的相关对象合并时,不会保留新关系,python,sqlalchemy,Python,Sqlalchemy,当我尝试更新数据时,我的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.Mod

当我尝试更新数据时,我的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更新父级和子级。在我的示例中,家长已经有一个孩子,我尝试向其中添加两个新孩子:

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语句。

我最终发现,如果在没有“id\u Child”的情况下删除它,合并就可以正常工作。 像这样:

second_json = {
    "id_parent": 1,
    "name": "parent1",
    "childrens": [
        {"id_child": 1, "name": "john"},
        {"name": "foo"},
        {"name": "bar"},
    ],
}

我用一个更完整的代码示例来编辑我的文章。我提供的代码实际上是有效的,并且我没有成功地重现我的应用程序的确切组成。