【问题标题】:How can I load initial data into a database using sqlalchemy如何使用 sqlalchemy 将初始数据加载到数据库中
【发布时间】:2013-07-01 22:13:08
【问题描述】:

我希望能够在使用 SQLAlchemy 创建表时自动加载数据。

在 django 中,您有 fixtures,它允许您在创建表时轻松地使用数据预先填充数据库。我发现这很有用,尤其是当您有基本的“查找”表时,例如product_type、student_type 只包含几行甚至是像货币这样的表格,它们将加载世界上所有的货币,而您在销毁模型/类时不必一遍又一遍地键入它们。

我当前的应用程序没有使用 django。我有 SQLAlchemy。我怎样才能达到同样的目的?我希望应用程序知道这是第一次创建数据库,因此它会用数据填充一些表。

【问题讨论】:

    标签: python django sqlalchemy


    【解决方案1】:

    我使用事件侦听器在创建表时使用数据预填充数据库。

    假设您的代码中有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)
    

    【讨论】:

    • event.listen 的代码在哪里,它使用了哪些导入/对象?
    • 我把事件监听器放在全局范围内,就在insert_data函数的定义下。我更新了缺少导入语句的答案,希望对您有所帮助。
    【解决方案2】:

    简短的回答是否定的,SQLAlchemy 不像 Django 那样提供与 dumpdata 和 loaddata 相同的功能。

    https://github.com/kvesteri/sqlalchemy-fixtures 可能对您有用,但工作流程不同。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-09-19
      • 1970-01-01
      • 2015-10-02
      • 1970-01-01
      • 1970-01-01
      • 2016-04-14
      • 1970-01-01
      相关资源
      最近更新 更多