【问题标题】:SQLAlchemy Automap does not create class for tables without primary keySQLAlchemy Automap 不会为没有主键的表创建类
【发布时间】:2014-07-09 01:29:41
【问题描述】:

我正在使用具有自动映射功能的 SQL Alchemy v(0.9.1)。这允许我自动创建类和关系。 http://docs.sqlalchemy.org/en/rel_0_9/orm/extensions/automap.html

我遇到的问题是,在使用 automap_base 时,我发现并非 metadata.tables 列表中可用的所有表都已映射。

准备时没有错误,只是在调用 automap_base() 后我无法从 Base 访问类(例如 Base.classes.Example_Table)

from sqlalchemy import create_engine, MetaData
from sqlalchemy.orm import create_session

from sqlalchemy.ext.automap import automap_base

engine = create_engine("mysql+mysqldb://")

Base = automap_base()
Base.prepare(engine, reflect = True)

session = create_session(bind = engine)

然后我运行发现元数据中的所有表都不存在类(我没有在元数据中使用 only = [] 参数)

for mappedclass in Base.classes:
    print mappedclass

for mdtable in metadata.tables:
    print mdtable

才发现Example_Table(用下面的create语法)没有类

    CREATE TABLE `Example_Table` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `attributeType` varchar(255) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3290719 DEFAULT CHARSET=latin1

即Base.class.Example_Table 返回以下错误

    ---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-15-94492ae1b8ba> in <module>()
      7 type(metadata.tables)
      8 
----> 9 Base.classes.Example_Table

/usr/local/lib/python2.7/site-packages/sqlalchemy/util/_collections.pyc in __getattr__(self, key)
    172             return self._data[key]
    173         except KeyError:
--> 174             raise AttributeError(key)
    175 
    176     def __contains__(self, key):

AttributeError: Example_Table

我认为这个问题不会发生,因为我的 Example_Table 名称中有一个下划线。

我认为问题与我的 Example_Table 没有主键这一事实有关。 Example_Table 仅用于链接其他两个表。

【问题讨论】:

    标签: python sqlalchemy


    【解决方案1】:

    通过梳理参考/重新构建问题来解决。

    万一它对别人有帮助-

    因为 SQLAlchemy ORM 基于身份映射模型,所以无法映射(或自动映射)没有主键的表。应指定任意主键。

    http://docs.sqlalchemy.org/en/latest/faq/ormconfiguration.html#how-do-i-map-a-table-that-has-no-primary-key

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-12-01
      • 1970-01-01
      • 1970-01-01
      • 2011-04-29
      • 1970-01-01
      相关资源
      最近更新 更多