On 08/30/2016 10:52 PM, [email protected] 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 [email protected]
<mailto:[email protected]>.
For more options, visit https://groups.google.com/d/optout.

--
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 [email protected].
For more options, visit https://groups.google.com/d/optout.

Reply via email to