Session: How to Evict Single Entity from a Session

We can clear all session operations and stop tracking of all entities using the clear method, but sometimes there's a need to do cleanup only for one entity. This is what evict is for.


def evict(self, entity: object) -> None: ...
Parameter Type Description
entity object Instance of an entity that will be evicted

Example I

employee_1 = Employee(first_name="John", last_name="Doe")
employee_2 = Employee(first_name="Joe", last_name="Shmoe")


session.save_changes()  # only 'Joe Shmoe' will be saved

Example II

employee = session.load("employees/1-A")  # loading from server
employee = session.load("employees/1-A")  # no server call
employee = session.load("employees/1-A")  # loading form server