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.

Syntax

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.store(employee_1)
session.store(employee_2)

session.advanced.evict(employee_1)

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
session.advanced.evict(employee)
employee = session.load("employees/1-A")  # loading form server