On Aug 26, 2014, at 7:42 AM, alchemy1 <[email protected]> wrote:

> I have these classes, with a one-to-many relationship from User to Thing. 
> Thing has a composite primary key of the user_uuid and the thing_type.
> 
> class User(Base):
>     ...
>     uuid = Column(UUID, primary_key=True)
>     things = relationship('Thing')
>     ...
> 
> class Thing(Base):
>     ...
>     user_uuid = Column(UUID, ForeignKey('user.uuid'), primary_key=True)
>     thing_type = Column(CHAR(2), primary_key=True)
>     ...
> 
> 
> 
> I have a web page that has several forms, one for each Thing associated with 
> the current user. A user can fill in say 3 of the forms and submit the form. 
> Here's how I process the form:
> 
> user = DBSession.query(User).options(joinedload('things')).filter(User.uuid 
> == authenticated_userid(request)).one()
> new_thing_list = []
> for new_thing in new_things:
>     new_thing_list.append(new_thing)
> user.things = new_thing_list  # Overwrite the old list of Things
> 
> 
> 
> I get the following error when trying to do it this way:
> 
> AssertionError: Dependency rule tried to blank-out primary key column 
> 'thing.user_uuid' on instance '<Thing at 0x7f80a45efc18>'
> 
> I figure it's because overwriting the old list of Things without deleting 
> each item first leads to orphans. So I change 'things' in User class to be:
> 
>     things = relationship('Thing', backref=backref('user', cascade='all, 
> delete-orphan'))
> 
> # Now I get this error
> # sqlalchemy.exc.ArgumentError: On Thing.user, delete-orphan cascade is not 
> supported on a many-to-many or many-to-one relationship when single_parent is 
> not set.   Set single_parent=True on the relationship().
> 

you put the "cascade='all, delete-oprhan'" on the *one-to-many* side, not the 
many-to-one side.  This is sometimes non-intuitive, so there's a green sidebar 
that gets into this in this section: 
http://docs.sqlalchemy.org/en/rel_0_9/orm/session.html#delete  called 
"ORM-level "delete" cascade vs. FOREIGN KEY level "ON DELETE" cascade".     
This doc section should probably be linked to a little more in the relationship 
docs.


-- 
You received this message because you are subscribed to the Google Groups 
"sqlalchemy" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to [email protected].
To post to this group, send email to [email protected].
Visit this group at http://groups.google.com/group/sqlalchemy.
For more options, visit https://groups.google.com/d/optout.

Reply via email to