在SQLAlchemy中编写连接错误:sqlalchemy.exc.InvalidRequestError:

时间:2016-07-20 20:19:29

标签: python sqlalchemy

这是我创建的第一个表

class Candidate(Base):
  __tablename__ = 'candidates'
  id = Column(Integer, primary_key=True)
  first = Column(String, nullable=False)
  last = Column(String)
  title = Column(String)
  company = Column(String, nullable=False)


  def __repr__(self):
    return "<Candidate(first='%s', last='%s', title = '%s', company='%s')>" % (self.first, self.last, self.title, self.company)

## Add user
morgan = Candidate(first='john', last='doe', title='some_title', company='some_company')
session.add(morgan)
session.commit()

我得到了这个查询:

morgan = session.query(Candidate).filter(Candidate.first=='morgan').first()

但是当我添加第二张表时,它就会停止工作。

class Roles(Base):
  __tablename__ = 'role'
  id = Column(Integer, primary_key=True)
  role = Column(String, nullable=False)
  user_id = Column(Integer, ForeignKey('candidates.id'))

  user = relationship("Candidate", back_populates="role")

  def __repr__(self):
    return "<Roles(role='%s')>" % (self.role)

我假设我做错了:

Candidate.role = relationship("Roles", order_by=Roles.id, back_populates='user')

再次尝试此搜索

morgan = session.query(Candidate).filter(Candidate.first=='morgan').first()

我收到此错误

sqlalchemy.exc.InvalidRequestError: One or more mappers failed to initialize - can't proceed with initialization of other mappers.  Original exception was: Mapper 'Mapper|Candidate|candidates' has no property 'role'

1 个答案:

答案 0 :(得分:0)

我对SQLAlchemy很新,但我认为您需要将角色表下的加入关系更新为:

user = relationship("Candidate", back_populates="role", order_by=id).