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().
So I add single_parent=True to 'things' in User class:
things = relationship('Thing', backref=backref('user', cascade='all,
delete-orphan', single_parent=True))
# Back to the original error
# AssertionError: Dependency rule tried to blank-out primary key column
'thing.user_uuid' on instance '<Thing at 0x7f80a45efc18>'
How can I get this to work? Does it have something to do with Thing having
a composite primary key?
I'm probably not handling this the best way where I'm throwing away the old
list each time the form gets submitted and overwriting it with all new
values, but I can't see another way to do it unless I give each Thing its
own primary key identity (and not a composite), which I'd prefer not to do.
--
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.