pygabriel
pygabriel

Reputation: 10008

sqlalchemy cascade and association objects

My database structure is something like this (I'm using declarative style):

class Character(Base):
    __tablename__="characters"
    id = Column(Integer, primary_key=True)
    name = Column(String)
    player = Column(String)
    inventory = relation(Inventory)

class Item(Base):
    __tablename__="items"
    id = Column(Integer, primary_key=True)
    name = Column(String)

class Inventory(Base):
    __tablename__="inventory"
    id = Column(Integer, primary_key=True)
    char_id = Column(Integer, ForeignKey("characters.id"))
    item_id = Column(Integer, ForeignKey("characters.id"))
    quantity = Column(Integer)
    item = relation(Item)

My problem is that when I remove an "Inventory" object from "Character.inventory" this isn't updated until the session get committed. For example:

>>> torch_inv=character.inventory[0] # Inventory object referred to a torch
>>> torch_inv.item, torch_inv.quantity
(<Item object, torch>, 3)
>>> session.delete(torch_inv)
>>> character.inventory[0]
<Inventory object, torch>

I've seen that there is a relation option "cascade" but I can't find a way to make it working in this case.

Upvotes: 0

Views: 990

Answers (1)

Denis Otkidach
Denis Otkidach

Reputation: 33200

Session.delete() method just marks an instance as "to be deleted", so your relation won't change untill you flush changes to database independent on cascade rules. On other hand you can just remove Inventory instance from character.inventory collection, then having 'delete-orphan' cascade rule will mark removed Inventory instance for deletion.

Upvotes: 1

Related Questions