[英]SqlAlchemy query result outputting
我正在嘗試使用Python 3中的SqlAlchemy在Postgres數據庫中查詢我的一個表。它可以很好地運行查詢,但是當我遍歷SqlAlchemy返回結果的每一行時,我嘗試使用屬性'text'(其中之一我的列名)。 我收到此錯誤:
'str' object has no attribute 'text'
我已經像這樣打印了屬性:
for row in result:
print(row.text)
這不會給出錯誤。 產生錯誤的代碼如下。 但是,給我的環境:
我有兩台服務器正在運行。 一個用於我的數據庫,另一個用於我的python服務器。
數據庫服務器:
Postgres v9.6
在亞馬遜的RDS上 帶有Python的服務器
Linux 3.13.0-65-generic x86_64
在Amazon EC2實例上 SqlAlchemy v1.1.5
Python v3.4.3
Flask 0.11.1
相關文件:
import sqlalchemy as sa
from sqlalchemy.ext.automap import automap_base
from sqlalchemy.orm import Session
import re
from nltk import sent_tokenize
class DocumentProcess:
def __init__(self):
...
Engine = sa.create_engine(
CONFIG.POSTGRES_URL,
client_encoding='utf8',
pool_size=20,
max_overflow=0
)
# initialize SQLAlchemy
Base = automap_base()
# reflect the tables
Base.prepare(Engine, reflect=True)
# Define all needed tables
self.Document = Base.classes.documents
self.session = Session(Engine)
...
def process_documents(self):
try:
offset = 5
limit = 50
###### This is the query in question ##########
result = self.session.query(self.Document) \
.order_by(self.Document.id) \
.offset(offset) \
.limit(limit)
for row in result:
# The print statement below does print out the text
print(row.text)
# when passing document.text to sent_tokenize, it
# gives the following error:
# 'str' object has no attribute 'text'
snippets = sent_tokenize(row.text.strip('\n')) # I have removed strip, but the same problem
except Exception as e:
logging.info(format(e))
raise e
這是我的PostgreSQL數據庫中的Document模型:
class Document(db.Model):
__tablename__ = "documents"
id = db.Column(db.Integer, primary_key=True)
text = db.Column(db.Text)
tweet = db.Column(db.JSON)
keywords = db.Column(db.ARRAY(db.String), nullable=True)
def to_dict(self):
return dict(
id=self.id,
text=self.text,
tweet=self.tweet,
keywords=self.keywords
)
def json(self):
return jsonify(self.to_dict())
def __repr__(self):
return "<%s %r>" % (self.__class__, self.to_dict())
我嘗試過的事情
以前,我在Document查詢中沒有order_by
。 這以前工作。 但是,即使刪除order_by
也無法修復它。
使用SELECT語句並手動檢查結果,但結果仍然相同
我沒有嘗試過
任何對此問題的想法將不勝感激。
事實證明, text
是PostgreSQL中的保留字。 我重命名了列名並重構了我的代碼以使其匹配。 這解決了問題。
如果創建外部表並且列數據類型之一是text
,則在PostgreSQL中可能會出現此錯誤。 將character varying()
更改為character varying()
,錯誤消失!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.