diff --git a/care/facility/events/handler.py b/care/facility/events/handler.py index 4c5193aa0f..53c3ffc6ba 100644 --- a/care/facility/events/handler.py +++ b/care/facility/events/handler.py @@ -79,8 +79,8 @@ def create_consultation_events( consultation_id: int, objects: list | QuerySet | Model, caused_by: int, - created_date: datetime = None, - taken_at: datetime = None, + created_date: datetime | None = None, + taken_at: datetime | None = None, old: Model | None = None, fields_to_store: list[str] | set[str] | None = None, ): diff --git a/care/utils/event_utils.py b/care/utils/event_utils.py index c5032e25bd..12d0dca91a 100644 --- a/care/utils/event_utils.py +++ b/care/utils/event_utils.py @@ -30,23 +30,28 @@ def get_changed_fields(old: Model, new: Model) -> set[str]: def serialize_field(object: Model, field_name: str): if "__" in field_name: field_name, sub_field = field_name.split("__", 1) - related_object = getattr(object, field_name) + related_object = getattr(object, field_name, None) return serialize_field(related_object, sub_field) - field = None + value = None + try: + value = getattr(object, field_name) + except AttributeError: + if object is not None: + logger.warning( + f"Field {field_name} not found in {object.__class__.__name__}" + ) + return None + try: - field = object._meta.get_field(field_name) - except FieldDoesNotExist as e: - try: - # try to get property field - return getattr(object, field_name) - except AttributeError: - raise e - - value = getattr(object, field.name, None) - if issubclass(field.__class__, Field) and field.choices: # serialize choice fields with display value - return getattr(object, f"get_{field.name}_display", lambda: value)() + field = object._meta.get_field(field_name) + if issubclass(field.__class__, Field) and field.choices: + value = getattr(object, f"get_{field_name}_display", lambda: value)() + except FieldDoesNotExist: + # the required field is a property and not a model field + pass + return value