I have two tables with a ManyToMany relation between them. Sometimes I need to refresh the database so I delete elements from both tables. However relations between deleted rows are still stored inside the automatically created intermediary table.
为了澄清问题,这里是一部小法典:
from elixir import *
metadata.bind = "sqlite:///test.db"
metadata.bind.echo = True
options_defaults[ shortnames ] = True
class A(Entity):
name = Field(Unicode(128))
blist = ManyToMany("B",cascade= all,delete, delete-orphan )
class B(Entity):
name = Field(Unicode(128))
alist = ManyToMany("A",cascade= all,delete, delete-orphan )
setup_all()
create_all()
a1 = A()
a1.name = u"john"
b1 = B()
b1.name = u"blue"
a1.blist.append(b1)
session.commit()
session.query(A).delete()
session.query(B).delete()
session.commit()
倾斜数据库现在包括:
sqlite> .dump
PRAGMA foreign_keys=OFF;
BEGIN TRANSACTION;
CREATE TABLE a (
id INTEGER NOT NULL,
name VARCHAR(128),
PRIMARY KEY (id)
);
CREATE TABLE b (
id INTEGER NOT NULL,
name VARCHAR(128),
PRIMARY KEY (id)
);
CREATE TABLE b_alist__a_blist (
a_id INTEGER NOT NULL,
b_id INTEGER NOT NULL,
PRIMARY KEY (a_id, b_id),
CONSTRAINT a_blist_fk FOREIGN KEY(a_id) REFERENCES a (id),
CONSTRAINT b_alist_fk FOREIGN KEY(b_id) REFERENCES b (id)
);
INSERT INTO "b_alist__a_blist" VALUES(1,1);
COMMIT;
我想在删除1或b1时,将“alist_a_blist”表格排除在外。
如果没有使用并非始终得到QQQ支持的DELETE声明,这种可能性是可能的。
自2006年以来 我肯定不是唯一与埃尔克斯尔有多彩关系的人,解决这一问题可能是微不足道的。
以上所述守则会产生q化警报:
sqlalchemy/orm/properties.py:842: SAWarning: On B.alist, delete-orphan cascade is not supported on a many-to-many or many-to-one relationship when single_parent is not set. Set single_parent=True on the relationship().
self._determine_direction()
这只是因为我现在随意试图在“Tomany”关系中增加校外选择。 这应当表明删除汉语不是正确的选择。