我有这两个表:
class Performance(Base):
__tablename__ = 'performances'
id_ = Column(Integer, Sequence('performance_id_seq'), primary_key=True)
competitor_id = Column(Integer, ForeignKey('competitors.id_'), index=True)
start_date = Column(DateTime, nullable=False, index=True)
end_date = Column(DateTime, nullable=False, index=True)
target = Column(Float, nullable=True)
actual = Column(Float, nullable=True)
competitor = relationship("Competitor", backref="performances")
class TargetAdjustment(Base):
__tablename__ = 'target_adjustments'
id_ = Column(Integer, Sequence('target_adjustments_id_seq'), primary_key=True)
competitor_id = Column(Integer, index=True)
start_date = Column(DateTime, nullable=False)
value = Column(Float, nullable=True)
__table_args__ = (ForeignKeyConstraint([competitor_id, start_date], [Performance.competitor_id, Performance.start_date]), {})
performance = relationship('Performance', backref=backref("adjustment", uselist=False))
Index('target_adjustment_index', TargetAdjustment.competitor_id, TargetAdjustment.start_date, unique=True)
(除其他外,但这些是我的问题的关键)
现在我需要从这些表中删除记录,但是当它们都包含记录时我无法删除它们!
我这样做:
competition = competitor.competition
adjustment_query = DBSession.query(TargetAdjustment).filter(
TargetAdjustment.competitor_id == competitor.id_
).filter(
or_(
TargetAdjustment.start_date <= competition.start_date,
TargetAdjustment.start_date >= competition.end_date
)
)
# delete any extraneous adjustment data for this competitor
log.warning("before: {}".format(adjustment_query.count()))
adjustment_query.delete()
DBSession.flush()
log.warning("after: {}".format(adjustment_query.count()))
# delete any extraneous performance data for this competitor
DBSession.query(Performance).filter(
Performance.competitor_id == competitor.id_
).filter(
or_(
Performance.start_date <= competition.start_date,
Performance.end_date >= competition.end_date
)
).delete()
DBSession.flush()
当我尝试删除“表演”记录时,日志声明表明我删除了等效的'target_adjustments'记录,
WARNI:之前:0
WARNI:之后:0
但我仍然遇到这个错误。
“IntegrityError:(IntegrityError)(1451,'无法删除或更新父行:外键约束失败 (
target_adjustments
,CONSTRAINTtarget_adjustments_ibfk_1
外键(competitor_id
,start_date
)参考performances
(competitor_id
,start_date
))')'从表演中删除 performances.competitor_id =%s AND(performances.start_date&lt; =%s OR performance.end_date&gt; =%s)'(1128L,datetime.datetime(2016,3,31, 23,0),datetime.datetime(2016,6,1,23,0))“
为什么我不能删除表演记录?
答案 0 :(得分:0)
我解决了。
我的删除查询实际上并未匹配所有记录,因此当我尝试删除性能时,表中仍有调整记录。
更新的代码如下:
adjustment_query = DBSession.query(TargetAdjustment).filter(
TargetAdjustment.competitor_id == competitor.id_
).filter(
or_(
TargetAdjustment.start_date <= competition.start_date,
TargetAdjustment.start_date >= (competition.end_date - timedelta(days=1)) # adjust to match performance end date query
)
)
幸运的是,我知道表演总是只有一天 - 现在。