I have a simple parent-child table relationship setup with SQL Alchemy (using SQLite). I am trying to get the children automatically deleted when the parent is deleted.
I have read several posts here and Googled but am still stumped what I am missing.
class Portfolio(Base):
__tablename__ = 'portfolio'
id = Column(Integer, primary_key=True)
name = Column(String)
holdings = relationship("Portfolio_Holdings", cascade='all,delete')
class Portfolio_Holdings(Base):
__tablename__ = "portfolio_holdings"
id = Column(Integer, primary_key=True)
portfolio_id = Column(Integer, ForeignKey('portfolio.id'))
ticker = Column(String)
When I delete a record in Portfolio, nothing related in Portfolio Holdings is deleted.
Creating records:
portfolio=Portfolio()
portfolio.name = "Some Name"
tickers = ['ABCD','EFGH','JKLI']
holdings_to_db = []
for ticker in tickers:
holding=Portfolio_Holding()
holding.ticker = ticker
holdings_to_db.append(holding)
portfolio.holdings = holding_to_db
Session.merge(portfolio)
All the records make it in the the database; however, when I delete Portfolio, nothing is deleted from Portfolio Holdings using the following code:
session = Session()
session.query(Portfolio).delete()
session.commit()
However, this works, as someone pointed out:
portfolio = session.query(Portfolio).filter(Portfolio.id==1).one()
session.delete(portfolio)
As mature as SQL Alchemey is, I wouldn't think one would work but the other wouldn't. Still makes me think I am missing something.