SQLAlchemy 关系错误:对象没有属性“c”

Posted

技术标签:

【中文标题】SQLAlchemy 关系错误:对象没有属性“c”【英文标题】:SQLAlchemy Relationship Error: object has no attribute 'c' 【发布时间】:2013-07-04 14:43:52 【问题描述】:

我使用sqlautocode 来生成我的模型和所有关系。我正在尝试做一个简单的查询,比如

obj = session.query(Venue).filter(Venue.symbol=="CARNEGIE_HALL").one()

由于某种原因,我不断收到此错误消息:

File "/usr/lib64/python2.6/site-packages/sqlalchemy/orm/relationships.py", line 331, in _annotate_present_fks
          secondarycols = util.column_set(self.secondary.c)
      AttributeError: 'Event' object has no attribute 'c'

如果我注释掉关系定义,那么上面的查询就会起作用。 sqlautocode 生成的关系定义对我来说很合适,但我是 SqlAlchemy 的新手。我不知道如何解决这个问题。我尝试从关系()更改为关系(),但我仍然得到同样的错误。

使用 sqlalchemy 0.8.2 和 sqlautocode 0.6。

请注意,Event 和 Event_Type 之间存在多对一关系,Event 和 Venue 之间存在多对一关系。

model.py

DeclarativeBase = declarative_base()
metadata = DeclarativeBase.metadata
metadata.bind = engine

Event = Table(u'Event', metadata,
    Column(u'id', INTEGER(), primary_key=True, nullable=False),
    Column(u'venue_id', INTEGER(), ForeignKey('Venue.id'), nullable=False),
    Column(u'event_type_id', INTEGER(), ForeignKey('Event_Type.id'), nullable=False),
)

Venue = Table(u'Venue', metadata,
    Column(u'id', INTEGER(), ForeignKey('Obj.id'), primary_key=True, nullable=False),
    Column(u'venue_type_id', INTEGER(), ForeignKey('Venue_Type.id'), nullable=False),
    Column(u'name', VARCHAR(length=100), nullable=False),
    Column(u'symbol', VARCHAR(length=50), nullable=False),
)

class Event(DeclarativeBase):
    __table__ = Event


    #relation definitions
    Event_Type = relation('EventType', primaryjoin='Event.event_type_id==EventType.id')
    Venue = relation('Venue', primaryjoin='Event.venue_id==Venue.id')


class EventType(DeclarativeBase):
    __tablename__ = 'Event_Type'

    __table_args__ = 

    #column definitions
    code = Column(u'code', VARCHAR(length=50), nullable=False)
    description = Column(u'description', VARCHAR(length=250))
    id = Column(u'id', INTEGER(), primary_key=True, nullable=False)
    name = Column(u'name', VARCHAR(length=100), nullable=False)

    #relation definitions
    Venues = relation('Venue', primaryjoin='EventType.id==Event.event_type_id', secondary=Event, secondaryjoin='Event.venue_id==Venue.id')


class Venue(DeclarativeBase):
    __table__ = Venue


    #relation definitions
    Event_Types = relation('EventType', primaryjoin='Venue.id==Event.venue_id', secondary=Event, secondaryjoin='Event.event_type_id==EventType.id')

错误日志

  mod_wsgi (pid=10861): Exception occurred processing WSGI script '/home/uname/web/html/foo/app/main.py'.
  Traceback (most recent call last):
    File "/home/uname/web/html/foo/app/main.py", line 208, in application
      return callback(environ, start_response)
    File "/home/uname/web/html/foo/app/main.py", line 68, in monitor
      obj = session.query(Venue).filter(Venue.symbol=="CARNEGIE_HALL").one()
    File "/usr/lib64/python2.6/site-packages/sqlalchemy/orm/session.py", line 1106, in query
      return self._query_cls(entities, self, **kwargs)
    File "/usr/lib64/python2.6/site-packages/sqlalchemy/orm/query.py", line 115, in __init__
      self._set_entities(entities)
    File "/usr/lib64/python2.6/site-packages/sqlalchemy/orm/query.py", line 124, in _set_entities
      self._set_entity_selectables(self._entities)
    File "/usr/lib64/python2.6/site-packages/sqlalchemy/orm/query.py", line 157, in _set_entity_selectables
      ent.setup_entity(*d[entity])
    File "/usr/lib64/python2.6/site-packages/sqlalchemy/orm/query.py", line 2728, in setup_entity
      self._with_polymorphic = ext_info.with_polymorphic_mappers
    File "/usr/lib64/python2.6/site-packages/sqlalchemy/util/langhelpers.py", line 614, in __get__
      obj.__dict__[self.__name__] = result = self.fget(obj)
    File "/usr/lib64/python2.6/site-packages/sqlalchemy/orm/mapper.py", line 1426, in _with_polymorphic_mappers
      configure_mappers()
    File "/usr/lib64/python2.6/site-packages/sqlalchemy/orm/mapper.py", line 2121, in configure_mappers
      mapper._post_configure_properties()
    File "/usr/lib64/python2.6/site-packages/sqlalchemy/orm/mapper.py", line 1243, in _post_configure_properties
      prop.init()
    File "/usr/lib64/python2.6/site-packages/sqlalchemy/orm/interfaces.py", line 231, in init
      self.do_init()
    File "/usr/lib64/python2.6/site-packages/sqlalchemy/orm/properties.py", line 1028, in do_init
      self._setup_join_conditions()
    File "/usr/lib64/python2.6/site-packages/sqlalchemy/orm/properties.py", line 1102, in _setup_join_conditions
      can_be_synced_fn=self._columns_are_mapped
    File "/usr/lib64/python2.6/site-packages/sqlalchemy/orm/relationships.py", line 115, in __init__
      self._annotate_fks()
    File "/usr/lib64/python2.6/site-packages/sqlalchemy/orm/relationships.py", line 311, in _annotate_fks
      self._annotate_present_fks()
    File "/usr/lib64/python2.6/site-packages/sqlalchemy/orm/relationships.py", line 331, in _annotate_present_fks
      secondarycols = util.column_set(self.secondary.c)
  AttributeError: 'Event' object has no attribute 'c'

【问题讨论】:

【参考方案1】:

你不能这样说:

Venues = relation('Venue', primaryjoin='EventType.id==Event.event_type_id', secondary=Event, secondaryjoin='Event.venue_id==Venue.id')

你需要这样说:

Venues = relation('Venue', primaryjoin='EventType.id==Event.event_type_id', secondary=Event.__table__, secondaryjoin='Event.venue_id==Venue.id')

“secondary”只需要一个 Table 对象,而不是映射类。

另请注意,SQLAlchemy 建议使用 association object pattern,而不是进行花哨的“辅助”设置,以使这种事情更简单。

【讨论】:

使用secondaryjoin,如何访问辅助表列?例如。我可以通过event_type = security_obj.Event_Types[0] 获取 Event_Type 对象。如何获取事件的标题? 使用关联对象模式。

以上是关于SQLAlchemy 关系错误:对象没有属性“c”的主要内容,如果未能解决你的问题,请参考以下文章

SQLAlchemy 子查询列表对象没有属性

与 SQLAlchemy 中不同的其他对象、自身和属性的多对多关系

flask wtforms sqlalchemy AttributeError:“str”对象没有属性“_sa_instance_state”

SqlAlchemy - 按关系属性过滤

SQLAlchemy:查询所有没有直接关系的对象

SQLAlchemy中的 backref具体用途