python - SQLAlchemy 属性错误 : 'Query' object has no attribute '_sa_instance_state' when retrieving from database

标签 python mysql sqlalchemy pyramid

问题是尝试使用 Pyramid 上的 SQLAlchemy 从数据库中检索具有关系的对象。我想要的基本上是创建我需要从数据库中检索的对象,以完成网页所需的数据。

当我尝试访问 url/poll/{id}(使用有效的轮询 ID,例如:/poll/1)以获取页面时,我收到此错误:AttributeError: 'Query' object has no attribute ' _sa_instance_state'。怎么了?

这是模型的相关部分:

class Question(Base):
    __tablename__ = 'question'
    id = Column(Integer, primary_key=True)
    text = Column(String(250))
    type_id = Column(Integer, ForeignKey('type.id'))
    type = relationship(Type)
    poll_id = Column(Integer, ForeignKey('poll.id'))
    poll = relationship(Poll)

    def __init__(self, text, type, poll):
        self.text = text
        self.type = type
        self.poll = poll


class Option(Base):
    __tablename__ = 'option'
    id = Column(Integer, primary_key=True)
    text = Column(String(250))
    question_id =  Column(Integer, ForeignKey('question.id'))
    question = relationship(Question)

    def __init__(self, text, question):
        self.text = text
        self.question = question

这是给我带来麻烦的代码部分。调试器指向倒数第二行(Option 对象)。

if request.matchdict['id'] != None:
            pinst = session.query(Poll).get(request.matchdict['id'])
            typeq = session.query(Type).first()
            qinst = session.query(Question).filter_by(poll=pinst)
            lopt = session.query(Option).filter_by(question=qinst)
            return {'question':qinst, 'arroptions':lopt, 'type':typeq}

提前致谢!

最佳答案

qinst 是一个查询,而不是一个问题。你可能想要:

qinst = session.query(Question).filter_by(poll=pinst).one()

qinst = session.query(Question).filter_by(poll=pinst).first()

您还可以在 Question 上添加一个反向引用,这样您就可以从 Poll 转到 Question:

class Question(Base):
    ...
    poll = relationship(Poll, backref="question")

qinst = pinst.question

关于python - SQLAlchemy 属性错误 : 'Query' object has no attribute '_sa_instance_state' when retrieving from database,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42183226/

相关文章:

python - 使用列表理解对多个数组执行 cumsum

python - 使倾斜图像周围的黑色轮廓变白opencv

mysql - MariaDB 相关子查询中 DateTimes 的截断

python - 如何在 SQLAlchemy 中使用子查询来生成移动平均线?

python - 随着时间的推移计算第二天有多少元素到达

python - 如何为给定 X、Y 坐标和时间的 2D 散点图设置动画,并带有出现和消失的点?

PHP 检查函数参数,如果为空则设置为空

php - 每个页面登录验证询问数据库

python - 使用变量访问 SQLAlchemy 表列名

python - 父实例未绑定(bind)到 Session;属性“帐户”的延迟加载操作无法进行