On Dec 21, 2012, at 7:14 AM, tonthon wrote:

> Hi,
> 
> I've got a joined inheritance :
> 
> class Task(Base):
>   __tablename__ = 'task'
>   id = Column(Integer, primary_key=True)
> 
> class Invoice(Task):
>  __tablename__ = 'invoice'
>   id = Column(ForeignKey("task.id"))
> 
> When I delete an invoice, the associated task is also deleted, that's ok.
> 
> I've got a model TaskStatus related to the Task object and I'd like all
> related status to be deleted when I delete an invoice:
> 
> class TaskStatus(Base):
>  __tablename__ = 'task_status'
>  id = Column(Integer, primary_key=True)
>  task_id = Column(ForeignKey("task.id"))
>  task = relationship("Task", backref=backref("statuses", cascade="all,
> delete-orphan"))        
> 
> How could I achieve that one ?

that mapping looks right to me, did you try it ?

an "ondelete='CASCADE'" can reduce the number of SELECT statements (see 
http://docs.sqlalchemy.org/en/rel_0_8/orm/collections.html#using-passive-deletes)
 but without it, "statuses" will load itself on flush and mark each of the 
TaskStatus objects for deletion.


from sqlalchemy import *
from sqlalchemy.orm import *
from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()

class Task(Base):
    __tablename__ = 'task'
    id = Column(Integer, primary_key=True)
    type_ = Column(String)
    __mapper_args__ = {'polymorphic_on': type_}

class Invoice(Task):
    __tablename__ = 'invoice'
    id = Column(ForeignKey("task.id"), primary_key=True)
    __mapper_args__ = {'polymorphic_identity': 'invoice'}


class TaskStatus(Base):
    __tablename__ = 'task_status'
    id = Column(Integer, primary_key=True)
    task_id = Column(ForeignKey("task.id"))
    task = relationship("Task", backref=backref("statuses",
                cascade="all, delete-orphan"))

e = create_engine("sqlite://", echo=True)
Base.metadata.create_all(e)

s = Session(e)

t1, t2, t3, t4 = TaskStatus(), TaskStatus(), TaskStatus(), TaskStatus()
i1 = Invoice(statuses=[t1, t2])
i2 = Invoice(statuses=[t3, t4])
s.add_all([i1, i2])

s.commit()

assert s.query(TaskStatus).count() == 4

s.delete(i1)
s.commit()

assert s.query(TaskStatus).count() == 2








-- 
You received this message because you are subscribed to the Google Groups 
"sqlalchemy" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to 
[email protected].
For more options, visit this group at 
http://groups.google.com/group/sqlalchemy?hl=en.

Reply via email to