我正在尝试从脚本中删除数据库中的表中的行。也许这不是最简单的方法,但我认为应该是可能的。我正在尝试以下方法:
from stemewebapp import app
from stemewebapp.models import Job, db
import sys
#
# Check arguments
#
if len(sys.argv) != 2:
print 'USAGE: %s <job uuid>' % (sys.argv[0])
sys.exit(-1)
job_uuid = sys.argv[1]
#
# Do everything in context
#
with app.test_request_context():
#
# Get job
#
query = db.session.query(Job).filter_by(uuid=job_uuid)
#query = Job.query.filter_by(uuid=job_uuid)
if 1 != query.count():
raise RuntimeError('Got more than one job by UUID.')
#
# Delete from database
#
db.session.delete(query.first())
db.session.commit()
我收到以下错误:
OperationalError: (OperationalError) no such table: job u'SELECT count(*) AS count_1 \nFROM (SELECT job.id AS job_id, job.creation_date AS job_creation_date, job.name AS job_name, job.uuid AS job_uuid, job.pid AS job_pid, job.completed AS job_completed \nFROM job \nWHERE job.uuid = ?) AS anon_1' ('743d952f-9cfc-4efc-bfa5-58da67c4a131',)
答案 0 :(得分:2)
这不是正确的方法。
Sqlalchemy在查询对象上提供名称为one
的方法。
try:
obj = db.session.query(Job).filter_by(uuid=job_uuuid).one()
except NoResultFound:
raise
except MultipleResultsFound:
raise RuntimeError('Got more than one job by UUID.')
else:
db.session.delete(obj)
db.session.commit()
One()只获取一个结果,如果有多个结果,则会引发该异常。
错误表明表不存在。检查您是否访问了错误的数据库,或者您忘记了初始化数据库。目前的信息不足以帮助您。