我希望能够在使用SQLAlchemy创建表时自动加载数据。
在django中,您有fixtures,它使您可以在创建表时轻松地用数据预填充数据库。我发现这很有用,尤其是当您具有基本的“查找”表时,例如product_type,student_type仅包含几行甚至是一个表(如货币),它们将加载世界上所有的货币,而您在销毁模型/类时不必一遍又一遍地键入它们。
我当前的应用程序未使用django。我有SQLAlchemy。我怎样才能做到同一件事?我希望应用程序知道数据库是第一次创建的,因此它用数据填充了一些表。
最佳答案
我使用事件监听器在创建表时用数据预填充数据库。
假设您的代码中包含ProductType
模型:
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))
首先,您需要定义一个回调函数,该函数将在创建表时执行:
def insert_data(target, connection, **kw):
connection.execute(target.insert(), {'id': 1, 'name':'spam'}, {'id':2, 'name': 'eggs'})
然后,您只需添加事件监听器:
event.listen(ProductType.__table__, 'after_create', insert_data)
关于python - 如何使用sqlalchemy将初始数据加载到数据库中,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/17461251/