SQLAlchemy - get()只能用于单个映射类

时间:2014-02-13 03:04:54

标签: sqlalchemy

Noob to SQLAlchemy。 :/

在Windows 7上使用Python 2.7和SQLAlchemy 0.9.2。

我收到了消息

Traceback (most recent call last):
  File "test.py", line 46, in <module>
    result = Session().query(Table_Enum_country).get(1)
  File "c:\Python27\lib\site-packages\sqlalchemy-0.9.2-py2.7.egg\sqlalchemy\orm\query.py", line 786, in get
    mapper = self._only_full_mapper_zero("get")
  File "c:\Python27\lib\site-packages\sqlalchemy-0.9.2-py2.7.egg\sqlalchemy\orm\query.py", line 322, in _only_full_mapper_zero
    "a single mapped class." % methname)
sqlalchemy.exc.InvalidRequestError: get() can only be used against a single mapped class.

我有一个SQL Server 2012表定义如下: -

CREATE TABLE [dbo].[enum_countries](
    [created_at] [datetime] NULL,
    [updated_at] [datetime] NULL,
    [updated_by_id] [int] NULL,
    [created_by_id] [int] NULL,
    [name] [nvarchar](256) NULL,
    [description] [nvarchar](256) NULL,
    [_enabled] [bit] NULL,
    [nationality] [nvarchar](50) NULL,
    [id] [int] IDENTITY(1,1) NOT NULL,
    [code] [nvarchar](10) NULL,
 CONSTRAINT [PK__enum_countries__4CA06362] PRIMARY KEY CLUSTERED 
(
    [id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]

我的Python代码如下: -

import logging
logging.basicConfig(level=logging.DEBUG)

logging.getLogger("sqlalchemy").setLevel(logging.WARN)

from sqlalchemy import create_engine
from sqlalchemy import MetaData
from sqlalchemy import Table
from sqlalchemy.orm import sessionmaker

# Initialize SQLAlchemy Environment
db = create_engine(
          "mssql://user:password@localhost/localDB")
Session = sessionmaker(bind=db)
metadata = MetaData()

# Grab ALL tables in one hit.
# metadata.reflect(bind=db)

Table_Enum_country      = Table(u'enum_countries',      metadata, autoload=True, autoload_with=db)


result = Session().query(Table_Enum_country).get(1)
print result

我做错了什么?为什么我不能简单地“获取()”行? 如果有更好的方法可以做到这一点,我很满意:)

提前致谢。

...莱尔

1 个答案:

答案 0 :(得分:2)

Session.get()用于映射类,而不是sql实体,因为你应该使用Table.select()

session.execute(Table_Enum_country.select().where( Table_Enum_country.columns.id == 1))

或者,将表映射到类:

from sqlalchemy.orm import mapper
class EnumContries(object):
    pass
mapper(EnumContries, Table_Enum_country)

instance = session.query(EnumContries).get(1)