5

For the following function

def deleteMenuItem(restaurant_id,menu_id):
    if request.method == 'POST':
        item = session.query(MenuItem).filter_by(id = menu_id)
        session.delete(item)
        session.commit()
        return redirect(url_for('showMenu',restaurant_id =restaurant_id))
    else:
        return render_template('deletemenu.html',restaurant_id=restaurant_id,menu_id=menu_id)

When I try to delete an item. I get the following error

sqlalchemy.orm.exc.UnmappedInstanceError UnmappedInstanceError: Class 'sqlalchemy.orm.query.Query' is not mapped

The error can be fixed if I do the following change to the code

item = session.query(MenuItem).filter_by(id = menu_id).one()

I am not sure why the .one() fixes the problem. Since the query itself will always find one result. So why is the .one() needed?

2
  • 4
    .one() returns the object found. ...filter_by(...) returns a Query object. Commented Jan 26, 2016 at 12:46
  • @Holloway that's an answer. Commented Jan 26, 2016 at 12:48

1 Answer 1

11

The session.query(MenuItem).filter_by(id=menu_id) returns a Query object that can be used to filter or order the results, not the results themselves.

one() returns the first object the query finds.

When you try to delete the query, it complains that the Query object is not mapped.

Docs are here. The Query object also has a delete method that will delete all matched objects.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.