On Mar 10, 2008, at 9:19 AM, Christophe Alexandre wrote:

> Hi,
>
> Assuming you have a one-to-many type of relationship, say one user  
> has several roles.
>
> The underlying "role" table would hold one foreign key referring to  
> the user table.
>
> A properly written SA ORM allows you to write:
>
> user1.roles
>
> Now assuming you have just created a new user (user2), what is the  
> easiest way if you want to "copy" roles from user1?
>
> I tried:
>
> user2.roles = user1.roles
>
> But then it deletes the roles from user1.

my first impression is that a relation from "users" to "roles" is  
typically a many to many.  That you are looking to have the same roles  
present on more than one user implies this as well.  But we can still  
work with one-to-many.


> Same if I go through a copy.copy():
>
> import copy
> user2.roles = copy.copy(user1.roles)

copy is going to fail because its copying the full state of each user,  
including the primary key, instance key, and probably the _state which  
is putting your session into an invalid state.

>
> Does anyone have an idea? I would like to avoid going through a loop  
> and creating the roles one by one.

First I'd put a convenience method on Role to handle generating a new  
Role object with the same value:

def asnew(self):
     return Role(self.name, ...)

then I'd just use a list comprehension to make the copy:

user2.roles = [r.asnew() for r in user.roles]




--~--~---------~--~----~------------~-------~--~----~
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