SQLAlchemy在添加父对象时创建重复的子对象

时间:2018-12-18 09:38:20

标签: python python-3.x sqlalchemy

我在SqlAlchemy数据库中有一个简单的父子关系,我正在尝试向数据库中添加一个父对象。但是,当我这样做时,它将尝试首先强制添加所有子对象,而不是检查它们的存在或使用insert or ignore。这意味着将违反子对象的唯一约束。

#!/bin/python3.6

import sqlalchemy as sa
from sqlalchemy.ext.declarative import declarative_base
import sqlalchemy.orm as orm

Base = declarative_base()

class Child(Base):
    __tablename__ = "children"

    id = sa.Column(sa.Integer, unique=True, nullable=False, primary_key=True)

class Parent(Base):
    __tablename__ = "parents"

    id = sa.Column(sa.Integer, unique=True, nullable=False, primary_key=True)

    child_id = sa.Column(sa.Integer, sa.ForeignKey('children.id'), nullable=False)
    child = orm.relationship(Child)

engine = sa.create_engine("sqlite:///tmp.db")
Base.metadata.create_all(engine)
Session = orm.sessionmaker(bind=engine)
session = Session()

# Clear all parents, children
session.query(Child).delete()
session.query(Parent).delete()

# Add a child for id 1
session.add(Child(id=1))

# Add a parent with a child identical to the one we just added
# SqlAlchemy attempts to add a duplicate child object which violates the unique constraint of children.id
session.add(Parent(id=1, child=Child(id=1)))

session.commit()

有一种变通方法,是通过填充父项的child_id属性而不是其child属性,但是,对于许多关系(外键列不起作用)的情况,这不起作用存在于父对象/表本身中。有更好的方法来避免将重复的对象插入数据库吗?

0 个答案:

没有答案