I used an event listener to pre-populate the database with data when creating the table.
Let's say you have a ProductType model in your code:
from sqlalchemy import event, Column, Integer, String from sqlalchemy.ext.declarative import declarative_base Base = declarative_base() class ProductType(Base): __tablename__ = 'product_type' id = Column(Integer, primary_key=True) name = Column(String(100))
First, you need to define a callback function that will be executed when the table is created:
def insert_data(target, connection, **kw): connection.execute(target.insert(), {'id': 1, 'name':'spam'}, {'id':2, 'name': 'eggs'})
Then you just add an event listener:
event.listen(ProductType.__table__, 'after_create', insert_data)
source share