Skip to content

Commit

Permalink
Merge pull request #2348 from coronasafe/sainak/fix/null-field-serial…
Browse files Browse the repository at this point in the history
…ization

fix attribute error on null values in field serialization
  • Loading branch information
vigneshhari authored Aug 8, 2024
2 parents ee747c6 + 1e955a5 commit 8709830
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 15 deletions.
4 changes: 2 additions & 2 deletions care/facility/events/handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
):
Expand Down
31 changes: 18 additions & 13 deletions care/utils/event_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -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


Expand Down

0 comments on commit 8709830

Please sign in to comment.