外键不限制SQLAlchemy / SQLite中的数据

时间:2019-02-27 04:48:28

标签: sqlalchemy foreign-keys

我是SQLAlchemy的新手,而不是ORM的新手。

我想在SqlAlchemy 1.2.7中的两个表之间定义ForeignKey约束。一个简单但完整的示例如下:

Base = declarative_base()    

from sqlalchemy import create_engine, ForeignKey
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship
from sqlalchemy import Column, String

class Mother(Base):
    __tablename__ = 'mother'
    name = Column(String, primary_key=True)
    children = relationship('Child', back_populates='mother')


class Child(Base):
    __tablename__ = 'child'
    name = Column(String, primary_key=True)
    mother_name = Column(String, ForeignKey('mother.name'))
    mother = relationship('Mother', back_populates='children')

engine = create_engine('sqlite:///:memory:', echo=True)
Base.metadata.create_all(engine)
Session = sessionmaker(bind=engine)
session = Session()

liz = Mother(name='Liz')
session.add(liz)
no_such_parent = Child(name='Sally', mother_name='Melissa')
sam = Child(name='Sam', mother_name='Liz')
wilf = Child(name='Wilf', mother_name='Liz')
session.add(sam)
session.add(wilf)
session.add(no_such_parent)
for child in session.query(Child):
    print(child.name)

我希望在与母亲“ Melissa”(不在数据库中)创建一个孩子时,此代码会引发异常。

这应该会破坏ForeignKey(mother_name = Column(String, ForeignKey('mother.name'))的参照完整性规则。

但是代码运行没有任何错误,并将所有三个子代提交到数据库,如输出所示:

...
2019-02-27 14:09:24,193 INFO sqlalchemy.engine.base.Engine INSERT INTO mother (name) VALUES (?)
2019-02-27 14:09:24,193 INFO sqlalchemy.engine.base.Engine ('Liz',)
2019-02-27 14:09:24,195 INFO sqlalchemy.engine.base.Engine INSERT INTO child (name, mother_name) VALUES (?, ?)
2019-02-27 14:09:24,195 INFO sqlalchemy.engine.base.Engine (('Sam', 'Liz'), ('Wilf', 'Liz'), ('Sally', 'Melissa'))
2019-02-27 14:09:24,196 INFO sqlalchemy.engine.base.Engine COMMIT
2019-02-27 14:09:24,197 INFO sqlalchemy.engine.base.Engine BEGIN (implicit)
2019-02-27 14:09:24,198 INFO sqlalchemy.engine.base.Engine SELECT child.name AS child_name, child.mother_name AS child_mother_name 
FROM child
2019-02-27 14:09:24,198 INFO sqlalchemy.engine.base.Engine ()

Sam
Wilf
Sally

那么,当会话尝试将no_such_parent(“ Sally”)添加到数据库时,为什么没有参照完整性错误?

0 个答案:

没有答案