On Mar 29, 2010, at 4:20 PM, Rich wrote:

> How is the best way to restrict a delete on an item if it has a value
> in a many-to-many mapping?
> 
> For example:
> 
> I have three tables: User, Group, and UserGroup.  UserGroup is a many-
> to-many mapping table between User and Group.  User has a relation
> called 'groups' and Group has a relation called 'users'.  Pretty
> simple schema.
> 
> I want the ability to delete a group, but only if it is not used by a
> user in which case I want it to fail.  If I do 'session.delete(group)'
> it removes all the items in UserGroup so that it will always succeed.
> One obvious solution is to always check the length of the 'users'
> attribute whenever I want to remove a group.  Is there a more generic
> way to do this that I can specify at the mapper level?


you want the delete to fail if there *are* users associated or if there are 
*not* ?    for the "raise an error if users exist", the most efficient and 
generic way is to ensure the foreign key on UserGroup is not nullable and 
"delete" cascade isn't used.    if you wanted to dig an assertion into the 
mapper you could use a before_delete() extension.   



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

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

Reply via email to