在 2016年8月31日星期三 UTC+8下午9:56:29,Mike Bayer写道:
>
>
>
> On 08/30/2016 10:52 PM, bin604...@gmail.com <javascript:> wrote: 
> > I am using PostgreSQL and Alembic for migration. When I added new column 
> > to my User table Alembic generated migration with the following script: 
> > 
> > from alembic import op 
> > import sqlalchemy as sa 
> > import random 
> > 
> > def generate_toke(): 
> >     return random.random() 
> > 
> > def upgrade(): 
> >     op.add_column('user', sa.Column('token', sa.String(), nullable=True 
> )) 
> >     op.execute('some code here') 
> > 
> > What I actually want to do is autogenerating the value of token by the 
> > generate_toke function for existing data in my DB. 
> > 
> > Is there a solution? 
>
> Because this is a Python function, simplest way to run the actual 
> function (which might not be necessary, see below), run an update() 
> statement in a loop: 
>
>
>     from sqlalchemy import Table, MetaData, select 
>
>     # make a local Table object 
>     user_table = Table( 
>        'user', MetaData(), 
>
>        # whatever the primary key is goes here, for example "user_id" 
>        Column('user_id', Integer, primary_key=True), 
>
>        # then your token column 
>        Column('token', String()) 
>     ) 
>
>     connection = op.get_bind() 
>     for row in connection.execute(select([user_table.c.user_id])): 
>          connection.execute( 
>              user_table.update(). 
>              values(token=generate_token()). 
>              where(user_table.c.id == row['user_id']) 
>          ) 
>
> now, if the function is truly the "random()" function, good news. 
> Postgresql has that already.    So instead of all the above, just do: 
>
>
>      op.execute("update user set token=random()") 
>
>
>
> > 
> > 
> > Alembic`s onwer Michael Bayer redirect me there 
> > 
> > 
> https://bitbucket.org/zzzeek/alembic/issues/383/set-the-value-of-column-when-upgrading
>  
> > 
> > -- 
> > You received this message because you are subscribed to the Google 
> > Groups "sqlalchemy-alembic" group. 
> > To unsubscribe from this group and stop receiving emails from it, send 
> > an email to sqlalchemy-alembic+unsubscr...@googlegroups.com 
> <javascript:> 
> > <mailto:sqlalchemy-alembic+unsubscr...@googlegroups.com <javascript:>>. 
> > For more options, visit https://groups.google.com/d/optout. 
>

thanks for your great help!

and my solution is below:
    connection = op.get_bind()
    for user in connection.execute('select user_id from user'):
        token = random_token()
        connection.execute("update user set token = '%s' where user_id = 
%d"%(token, user[0])


-- 
You received this message because you are subscribed to the Google Groups 
"sqlalchemy-alembic" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to sqlalchemy-alembic+unsubscr...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to