我有一个包含1000个表的oracle db。我只想从20个表中读取。我使用过Automap extention&用于声明表类的元数据。
问题是有些表没有主键。
from config import E3_SQLALCHEMY_DATABASE_URI
from sqlalchemy import create_engine, MetaData, Column, String, Table
from sqlalchemy.orm import Session
from sqlalchemy.ext.automap import automap_base
engine = create_engine(E3_SQLALCHEMY_DATABASE_URI)
metadata = MetaData()
# auto-map db tables, list down the tables you want to query here
metadata.reflect(engine, only=['table_name1',
'table_name2',
'table_name3']}
Base = automap_base(metadata=metadata)
Base.prepare()
# db declaration
Table1 = Base.classes.table_name2
Table2 = Base.classes.table_name1
Table3 = Base.classes.table_name3
# create sqlalchemy session
session = Session(engine)
这导致Atrtibute错误,因为table3没有主键
我正在检查http://docs.sqlalchemy.org/en/rel_1_0/faq/ormconfiguration.html#how-do-i-map-a-table-that-has-no-primary-key,并试图在不直接更改db表的情况下添加主键。
我不知道该怎么做。 我尝试过这几种方式。但都有错误。这是table3的模式,但是没有声明主键。
class Table3(Base):
__table__ = 'table_name3'
__table_args__ = {'extend_existing': True}
# name = Column('name', String(1024), primary_key=True)
# collection_key = Column('name', String(8192), primary_key=True)
__mapper_args__ = {'primary_key': ['name', 'priority']}
我不想更改db表以添加primary_key,而是想在sqlalachemy中处理。因此,我尝试使用两个现有列,使用 mapper_args 声明主键。
In [40]: e3.query(FD_Group)
---------------------------------------------------------------------------
InvalidRequestError Traceback (most recent call last)
<ipython-input-40-6793c4942672> in <module>()
----> 1 e3.query(FD_Group)
C:\Python34\lib\site-packages\sqlalchemy\orm\session.py in query(self, *entities
, **kwargs)
1247 :class:`.Session`."""
1248
-> 1249 return self._query_cls(entities, self, **kwargs)
1250
1251 @property
C:\Python34\lib\site-packages\sqlalchemy\orm\query.py in __init__(self, entities
, session)
108 self.session = session
109 self._polymorphic_adapters = {}
--> 110 self._set_entities(entities)
111
112 def _set_entities(self, entities, entity_wrapper=None):
C:\Python34\lib\site-packages\sqlalchemy\orm\query.py in _set_entities(self, ent
ities, entity_wrapper)
116 self._primary_entity = None
117 for ent in util.to_list(entities):
--> 118 entity_wrapper(self, ent)
119
120 self._set_entity_selectables(self._entities)
C:\Python34\lib\site-packages\sqlalchemy\orm\query.py in __init__(self, query, c
olumn, namespace)
3576 raise sa_exc.InvalidRequestError(
3577 "SQL expression, column, or mapped entity "
-> 3578 "expected - got '%r'" % (column, )
3579 )
3580 elif not check_column:
InvalidRequestError: SQL expression, column, or mapped entity expected - got '<c
lass '__main__.FD_Group'>'
可以帮助如何在不添加数据库的情况下在Autobase中添加主列?