From 88a4cdd2acc772bd9709f52797751a894d97b7c9 Mon Sep 17 00:00:00 2001 From: Horilla Date: Thu, 6 Mar 2025 12:09:26 +0530 Subject: [PATCH] [UPDT] EMPLOYEE: Optimize email duplication check by excluding current instance during validation --- employee/forms.py | 27 ++++++++++++++++++--------- 1 file changed, 18 insertions(+), 9 deletions(-) diff --git a/employee/forms.py b/employee/forms.py index 2bbff1c87..ee4700b73 100644 --- a/employee/forms.py +++ b/employee/forms.py @@ -194,19 +194,28 @@ def as_p(self, *args, **kwargs): def clean(self): super().clean() email = self.cleaned_data["email"] - all_employees = Employee.objects.entire() - exit_employee = all_employees.filter(email=email).first() + query = Employee.objects.entire().filter(email=email) + if self.instance and self.instance.id: + query = query.exclude(id=self.instance.id) + + existing_employee = query.first() + + if existing_employee: + company_id = None + if ( + hasattr(existing_employee, "employee_work_info") + and existing_employee.employee_work_info + ): + company_id = existing_employee.employee_work_info.company_id - if exit_employee: - company_id = getattr( - getattr(exit_employee, "employee_work_info", None), "company_id", None - ) if company_id: error_message = _( - "Employee with this Email already exists in company {}" - ).format(company_id) + "An Employee with this Email already exists in company {}".format( + company_id + ) + ) else: - error_message = _(f"Employee with this Email already exists") + error_message = _("An Employee with this Email already exists") raise forms.ValidationError({"email": error_message})