Hi,

One easy/obvious improvement would be to delete all user's
"identifiers" and "groups" at once without iterating over them for
every user. Actually, iterating over the list of user_ids is not
necessary too I think.

<code>
session.query(Identifier).filter(Identifier.user_id.in_(user_ids)).delete()
session.query(User).filter(User.id.in_(user_ids)).delete()
</code>

I'm not sure about deleting "groups" in your code - I suppose you
don't want to delete the actual group but only the association between
the user and the group, i.e. the record from the intermediate table.
But the idea is the same - .filter(blah-
blah.user_id.in_(user_ids)).delete()

An even better solution would be to set up proper cascade rules on
your relationships so all "dependent" items are deleted automatically
when a user is deleted. Then the method will be a one-liner:

<code>
session.query(User).filter(User.id.in_(user_ids)).delete()
</code>


On Jun 1, 7:40 pm, Fabien Ribes <fri...@gmail.com> wrote:
> Hi,
>
> I have three tables (user, identifiers, groups) with 'many to one' and
> 'many to many' relationships. My code for deleting a user works
> correctly but I would like to have it run faster. What improvements do
> you suggest ?
>
> <code>
>     def delete_list(self, user_ids):
>         """Delete a list of users by id"""
>
>         session = self._get_orm_session()
>         for user_id in user_ids:
>             try:
>                 user = session.query(User).filter(User.id ==
> user_id).one()
>                 if user:
>                     # loop to free the user's identifiers
>                     for ident in user.identifiers:
>                         ident.user = None
>
>                     # loop to remove the user from the groups
>                     for group in user.groups:
>                         del group
>
>                     session.query(User).filter(User.id ==
> user_id).delete()
>             except NoResultFound, ex:
>                 raise SmartResourceNotFound("User not found " +
> str(ex))
>
>         session.commit()
> </code>

-- 
You received this message because you are subscribed to the Google Groups 
"sqlalchemy" group.
To post to this group, send email to sqlalchemy@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