Search code examples
pythonmysqluuid

Insert different UUID on each row of a large table by python


15

I have a table with ~80k rows with imported data. Table structure is as follows:

order_line_items

  • id
  • order_id
  • product_id
  • quantity
  • price
  • uuid

On import, the order_id, product_id, quantity, and price were imported, but the uuid field was left null.

Is there a way, using python's UUID() function, to add a uuid to each row of the table in bulk? I could use a script to cycle through each row and update it but if there is a python solution, that would be fastest.


Solution

  • Probably you need to add the default uuid for the table/model and and save value

    from uuid import uuid4
    from sqlalchemy import Column, String
    
    class Table(Base):
        __tablename__ = 'table'
    
        id = Column(String, primary_key=True, default=uuid4)
        # add other column
    
    records =[] # records in dict 
    sess = session() # database session
    
    # save all records in db
    sess.bulk_insert_mappings(Table, records)
    sess.commit()