Reputation: 1147
I'm trying to delete a row from a table in my database from a script. Perhaps this isn't the easiest way but I think it should be possible. I'm trying the following:
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()
I'm getting the following error:
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',)
Upvotes: 1
Views: 152
Reputation: 6036
This is not the right way.
Sqlalchemy provides method with name one
on query object.
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() fetches only one result and if there are multiple results then raises that exception.
Error suggests table does not exist. Check if you are accessing wrong database or you have forgotten to intialize database. Current information is insufficient to help you.
Upvotes: 2