【问题标题】:Create a table from a SQLAlchemy model with a different name?从具有不同名称的 SQLAlchemy 模型创建表?
【发布时间】:2015-11-28 07:23:15
【问题描述】:

我正在将 csv 文件中的数据导入使用 SQLAlchemy 声明性 API 创建的表中。

我收到了这些数据的更新,我想将这些更新暂存到一个具有相同结构的临时表中以进行预处理。

例如:

from sqlalchemy import Column,Integer
from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()

class MyModel(Base):
    __tablename__ = "mymodel"
    test_column = Column(Integer,primary_key=True)

我可以使用MyModel.__table__.create() 来创建这个表。

我可以使用类似的构造来创建另一个具有相同模型和不同名称的表吗?

实现这一目标的推荐方法是什么?

【问题讨论】:

  • 具体表继承可能会有所帮助,但也可能有点矫枉过正:docs.sqlalchemy.org/en/rel_1_0/orm/extensions/declarative/…
  • 我更喜欢@alecxe 的评论,但如果你想冒险,你可以这样做:tb2 = MyModel.__table__._clone(); tb2.name = "my_temp_table_name"; tb2.create()。但这使用了非公开的_clone(),你可能不得不忍受暗示。
  • 感谢大家的各种选择
  • @van 你不依赖 _clone() 是对的。在我的测试中,它最终调用了 Immutable 的 _clone(),它返回了 sqlalchemy 版本 1.0.8 中的原始实例。

标签: python sqlalchemy


【解决方案1】:

只需扩展您现有的表并更改其名称

class StagingMyModel(MyModel):
    __tablename__ = "staging_mymodel"

【讨论】:

  • 我也是这么想的,但是你得到了错误NoForeignKeysError: Can't find any foreign key relationships between 'mymodel' and 'staging_mymodel'
【解决方案2】:

这对我有用:

from sqlalchemy import Column,Integer
from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()

class MyBase(Base):
    __abstract__ = True

    test_column = Column(Integer,primary_key=True)

class MyModel(MyBase):
    __tablename__ = "mymodel"


class MyStagingModel(MyBase):
    __tablename__ = "mymodel_staging"

参考:https://docs.sqlalchemy.org/en/14/orm/declarative_tables.html#using-deferredreflection

另请参阅https://sparrigan.github.io/sql/sqla/2016/01/03/dynamic-tables.html,了解可能与您最初对ModelName.__table__.create() 的想法相吻合的方法。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-01-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-11
    相关资源
    最近更新 更多