【问题标题】:assigning specific column to be primary key when reflecting an existing table with sqlalchemy and turbogears使用 sqlalchemy 和 turbogears 反映现有表时将特定列分配为主键
【发布时间】:2011-11-19 16:10:05
【问题描述】:

这是一个项目的一部分,该项目涉及使用 tg2 处理其中一个数据库(该模型使用的是 mssql)。因为我需要读取/写入的表是使用不同的应用程序创建和管理的,所以我不希望 turbogears 覆盖/更改表 - 只需使用现有表 - 所以我使用 sqlalchemy 神奇的“自动加载”反射(我也不知道mssql db中这个表配置的每一个细节) 由于 tg2 内部工作,一些反射是在 model.__init__.py 而不是在课堂上完成的(正如一些 sqlalchemy 教程所建议的那样)

这是我收到的错误消息:(db 中的表名是 SOMETABLE,而在我的应用程序中,该类是活动)

sqlalchemy.exc.ArgumentError: Mapper Mapper|Activities|SOMETABLE could not
 assemble any primary key columns for mapped table 'SOMETABLE'

这是活动类:

class Activities(DeclarativeBase2):

    __tablename__ = 'SOMETABLE'
    #tried the classic way, I used in another place without tg but didn't work here -      the reflection should be outside the class
    #__table_args__=  {'autoload':True
                      #,'autoload_with':engine2
                     #}
    def __init__(self,**kw):
        for k,v in kw.items():
            setattr(self,k,v)

这是model.__init__.py init 模型方法(调用反射的地方):

def init_model(engine1,engine2):
    """Call me before using any of the tables or classes in the model."""
    DBSession.configure(bind=engine1)
    DBSession2.configure(bind=engine2)

    # If you are using reflection to introspect your database and create
    # table objects for you, your tables must be defined and mapped inside
    # the init_model function, so that the engine is available if you
    # use the model outside tg2, you need to make sure this is called before
    # you use the model.

    #
    # See the following example:
    metadata.bind = engine1
    metadata2.bind = engine2
    #metadata2=MetaData(engine2)

    global t_reflected
    #
    t_reflected = Table("SOMETABLE", metadata2,
        autoload=True, autoload_with=engine2)
    #
    mapper(Activities, t_reflected

所以我想我需要告诉 sqlalchemy 什么是主键 - 但是在使用反射时我该怎么做(我知道主键字段)?

编辑工作解决方案:

def init_model(engine1,engine2):
    """Call me before using any of the tables or classes in the model."""
    DBSession.configure(bind=engine1)
    DBSession2.configure(bind=engine2)

    # If you are using reflection to introspect your database and create
    # table objects for you, your tables must be defined and mapped inside
    # the init_model function, so that the engine is available if you
    # use the model outside tg2, you need to make sure this is called before
    # you use the model.

    #
    # See the following example:
    metadata.bind = engine1
    metadata2.bind = engine2
    #metadata2=MetaData(engine2)

    global t_reflected
    #
    t_reflected = Table("SOMETABLE", metadata2,String,primary_key=True),
        autoload=True, autoload_with=engine2)# adding the primary key column here didn't work
    #
    mapper(Activities, t_reflected, non_primary=True)# notice the needed non_primary - for some reason I can't do the whole mapping in one file and I Have to do part in init_model and part in the model - quite annoying

在模型中我也必须添加主键列:

class Activities(DeclarativeBase2):

__tablename__ = 'SOMETABLE'
#tried the classic way, I used in another place without tg but didn't work here -      the reflection should be outside the class
EVENTCODE = Column(String, primary_key=True)# needed because the reflection couldn't find the primary key .

当然,我还必须在 model.__init__.py 中添加各种导入来完成这项工作

奇怪的是,它甚至在连接到数据库之前抱怨没有找到主键,而当一个独立的 sqlalchemy 类(没有 tg2)执行相同的键时 - 根本没有抱怨。让你好奇

【问题讨论】:

    标签: sqlalchemy turbogears2


    【解决方案1】:

    您可以混合搭配:请参阅文档中的Overriding Reflected Columns。在您的情况下,代码看起来类似于:

    t_reflected = Table("SOMETABLE", metadata2,
        Column('id', Integer, primary_key=True), # override reflected '???' column to have primary key
        autoload=True, autoload_with=engine2)
    

    edit-1:模型版本:我也认为只有声明性版本也可以工作,在这种情况下你不应该定义一个表t_reflected,也不应该使用@手动映射那些987654324@ 因为声明性类是自动映射的:

    class Activities(DeclarativeBase2):
        __table__ = Table('SOMETABLE', metadata2,
            Column('EVENTCODE', Unicode, primary_key=True),
            autoload=True, autoload_with=engine2,
        )
        def __init__(self,**kw):
            for k,v in kw.items():
                setattr(self,k,v)
    

    【讨论】:

    • 谢谢,但有些东西仍然不起作用,我收到相同的错误消息(我将编辑我对问题所做的)和一些更神秘的 - 当我使用带有 autload 的类并调用直接没有涡轮齿轮的发动机一切正常!我做错了什么?
    • 不,此编辑不起作用 - 但您引导我找到了正确的解决方案,我将在编辑中详细说明
    • 解释:这会引发启动整个事情的错误 - 关于 not found the engine 。因为在 tg2 中你必须定义类外的反射。 (不了解内部工作,只是它的工作方式)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-13
    • 1970-01-01
    • 2019-10-29
    • 1970-01-01
    • 1970-01-01
    • 2017-08-17
    相关资源
    最近更新 更多