【发布时间】:2015-06-09 03:50:46
【问题描述】:
我正在尝试从我的数据库中删除delete 和order,同时删除与之相关的所有ordereditems。
with contextlib.closing(DBSession()) as session:
try:
returnedOrder = session.query(ORDER).filter_by(ORDERSID=orderID).first()
session.delete(returnedOrder)
session.commit()
except exc.SQLAlchemyError, error:
session.rollback()
raise_database_error(error)
else:
return '1'
这里是相关的classes(部分项目已被删除):
class ORDER(Base):
__tablename__ = 'ORDERS'
ORDERSID = Column(Integer, primary_key=True)
ORDERSCOST = Column(Numeric(19, 4), nullable=False)
ORDEREDITEM = relationship("ORDEREDITEM")
class ORDEREDITEM(Base):
__tablename__ = 'ORDEREDITEMS'
__table_args__ = (
Index('AK_ORDERSID_ITEMID', 'ORDERSID', 'ITEMSID', unique=True),
)
ORDEREDITEMSID = Column(Integer, primary_key=True)
ITEMSID = Column(ForeignKey(u'ITEMS.ITEMSID'), nullable=False, index=True)
ORDERSID = Column(ForeignKey(u'ORDERS.ORDERSID', ondelete=u'CASCADE'), nullable=False)
ORDEREDITEMSQUANTITY = Column(Integer, nullable=False)
ORDER = relationship(u'ORDER')
SQL 文件:
create table ORDERS
(
ORDERSID int not null auto_increment,
ORDERSCOST decimal(19,4) not null,
primary key (ORDERSID)
);
create table ORDEREDITEMS
(
ORDEREDITEMSID int not null auto_increment,
ORDERSID int not null,
ITEMSID int not null,
ORDEREDITEMSQUANTITY int not null,
primary key (ORDEREDITEMSID),
unique key AK_ORDERSID_ITEMID (ORDERSID, ITEMSID)
);
alter table ORDEREDITEMS add constraint FK_ORDER_ORDEREDITEM foreign key (ORDERSID)
references ORDERS (ORDERSID) on delete CASCADE on update restrict;
当我运行它时,我得到了错误:
(IntegrityError) (1452, 'Cannot add or update a child row: a foreign key constraint fails (`my_database`.`ordereditems`,
CONSTRAINT `FK_ORDER_ORDEREDITEM` FOREIGN KEY (`ORDERSID`) REFERENCES `ORDERS` (`ORDERSID`) ON DELETE CASCADE)')
'UPDATE `ORDEREDITEMS` SET `ORDERSID`=%s WHERE `ORDEREDITEMS`.`ORDEREDITEMSID` = %s' (None, 3L)
当我直接在 phpMyAdmin 上执行相同的操作时,它按预期工作。
【问题讨论】:
标签: python mysql sqlalchemy sql-delete