我希望能够在使用 SQLAlchemy 创建表时自动加载数据。
在 django 中,你有fixtures https://docs.djangoproject.com/en/dev/howto/initial-data/它允许您在创建表时轻松地用数据预填充数据库。我发现这很有用,特别是当您有基本的“查找”表时,例如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)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)