使用Flask和PostgresSQL时出错-sqlalchemy.exc.ProgrammingError:无法适应类型“ RowProxy”

时间:2019-08-01 16:39:55

标签: python postgresql flask

我正在根据在线教程创建一个书评网站。 似乎我正在将一些偏斜的值user_id传递到reviews表中。

假设user_id是一个纯整数(smallint),但是在错误消息中,它显示为(2,),我想知道这是否是导致此错误的主要原因。

我要使用的这种方法是显示一本书的详细页面,并让用户提交评论。因此,我从存储的会话中获取username,并使用它从user_id表中提取users并将其作为外键值{{1 }}

这是与该问题有关的路线。

review

这是错误消息!

enter image description here

请查看代码,并让我知道您认为问题出在哪里。 谢谢你的时间!

1 个答案:

答案 0 :(得分:1)

execute()始终为每一行返回一个列值的元组,即使您仅选择一列也是如此。更准确地说,它实际上是一个元组的包装,称为RowProxy(或当返回多行时为ResultProxy),为您提供了更多功能。我会稍微更改变量名称以强调这一点:

result = db.execute("SELECT id FROM users WHERE username = :username",{"username":username}).fetchone()
result.columns() # returns ('id',) - so you can create a dict of key value pairs
user_id = result[0]

尽管您也可以保持简洁(注意逗号)

user_id, = db.execute("SELECT id FROM users WHERE username = :username",{"username":username}).fetchone()

user_id = db.execute("SELECT id FROM users WHERE username = :username",{"username":username}).fetchone()[0]

更新

我认为到达多列的最干净方法是执行我在嵌入式注释中编写的内容,即创建键值对的字典。

result = db.execute("SELECT * FROM books WHERE isbn = :isbn", {"isbn": isbn}).fetchone()

# zip takes two lists and returns them as a list of tuples, combining
# the nth element of the first list and the nth element of the second list,
# so essentially it creates a list of key value pairs for you
book = {column: value for (column, value) in zip(result.columns(), result)}
book_id = book['id']

,或者在有多行的情况下:

result = db.execute("SELECT * FROM books WHERE author_id = :author_id", {"author_id": author_id}).fetchall()

books = [
    {column: value for (column, value) in zip(result.columns(), row)}
    for row in result
]
book_ids = [book['id'] for book in books]