'Transfers a team and all projects under it to the given organization.'

def transfer_to(self, organization):

    from sentry.models import OrganizationAccessRequest, OrganizationMember, OrganizationMemberTeam, Project, ReleaseProject
    try:
        with transaction.atomic():
            self.update(organization=organization)
    except IntegrityError:
        new_team = Team.objects.get(organization=organization, slug=self.slug)
    else:
        new_team = self
    project_ids = list(Project.objects.filter(team=self).exclude(organization=organization).values_list('id', flat=True))
    ReleaseProject.objects.filter(project_id__in=project_ids).delete()
    Project.objects.filter(id__in=project_ids).update(team=new_team, organization=organization)
    if (self != new_team):
        OrganizationAccessRequest.objects.filter(team=self).delete()
    old_memberships = OrganizationMember.objects.filter(teams=self).exclude(organization=organization)
    for member in old_memberships:
        try:
            new_member = OrganizationMember.objects.get(user=member.user, organization=organization)
        except OrganizationMember.DoesNotExist:
            continue
        try:
            with transaction.atomic():
                OrganizationMemberTeam.objects.create(team=new_team, organizationmember=new_member)
        except IntegrityError:
            pass
    OrganizationMemberTeam.objects.filter(team=self).exclude(organizationmember__organization=organization).delete()
    if (new_team != self):
        cursor = connections[router.db_for_write(Team)].cursor()
        try:
            cursor.execute('DELETE    FROM    sentry_team    WHERE    id    =    %s', [self.id])
        finally:
            cursor.close()
