python-3.xflaskflask-sqlalchemyflask-restful

sqlalchemy.orm.exc.UnmappedInstanceError: Class 'builtins.int' is not mapped


I am using flask_restful for my project, I am trying to delete an entry, but unable to do it. Following is the end point implementation:

def delete_from_db(self, emp_no):
    db.session.delete(emp_no)
    db.session.commit()

class DeleteEmployee(Resource):
    @marshal_with({
        'message': fields.String
    })
    def delete(self, employee_id: int):
        employee = db.get_or_404(
            Employees, employee_id,
            description='Employee Not Found'
        )
        employee.delete_from_db(emp_no=employee_id)
        return {
            'message': 'Employee Deleted successfully.'
        }

If I execute end point, , which is like that:

{{base_URL}}/employee/3

I am getting following response:

  File "/Users/tp/.pyenv/versions/3.7.13/lib/python3.7/site-packages/sqlalchemy/orm/session.py", line 3414, in delete
    raise exc.UnmappedInstanceError(instance) from err
sqlalchemy.orm.exc.UnmappedInstanceError: Class 'builtins.int' is not mapped

If comment the line of employee.delete_from_db(emp_no=employee_id), it will works fine, but it does not delete record from database.

What can be the problem?


Solution

  • To delete data, pass the model object to db.session.delete().

    @marshal_with({
        'message': fields.String
    })
    def delete(self, employee_id: int):
        employee = db.get_or_404(
            Employees, employee_id,
            description='Employee Not Found'
        )
        db.session.delete(employee)
        db.session.commit()
        return {
            'message': 'Employee Deleted successfully.'
        }
    

    In your case, with the instance method, it is possible to simply pass self.

    def delete_from_db(self):
        db.session.delete(self)
        db.session.commit()