InvalidRequestError: Instance '<User at 0x7f65938a7510>' is not persisted

16,462

Solution 1

You are trying to delete a new instance, rather than an instance you got from the database. Either you meant to use db.session.add(), or you meant to use user = User.query.filter_by(email='[email protected]').first() (or something similar) and delete that.

You might also have trouble accessing attributes of the deleted instance (assuming you delete it correctly as above). When you commit a session, all instances in that session are expired. Trying to access an expired attribute triggers a database lookup, but there can be no lookup for this object because it was deleted.

You can turn expire_on_commit off, but that is not the normal behavior and will probably cause you other problems.

You could also try calling make_transient on it.

Ultimately, you should really just abandon instances that have been deleted. There is probably a better way to do whatever you are trying to accomplish.

Solution 2

When you call

user = User(name="John", age=33, email="[email protected]")

you create python object, not object in db. So you need first add it to db

db.session.add(user)
db.session.commit()

after it you can delete it from db

db.session.delete(user)
db.session.commit()

and your assertNotEqual have no sence. You should test that result of select from db before and after delete is different

Share:
16,462
Mark
Author by

Mark

Updated on August 06, 2022

Comments

  • Mark
    Mark almost 2 years

    I want to perform such a test in the framework Flask and gets the message:

    InvalidRequestError: Instance '<User at 0x7f65938a7510>' is not persisted
    
      File "tests.py", line 31, in test_removeProfil
        db.session.delete(user)
    

    My test code:

    class TestCase(unittest.TestCase):
    
        def test_removeProfil(self):
            user = User(name="John", age=33, email="[email protected]")
            db.session.delete(user)
            db.session.commit()
            self.assertNotEqual(user.name, "John")
            self.assertNotEqual(user.age, 33)
            self.assertNotEqual(user.email, "[email protected]")