Skip to content

Commit

Permalink
refactor: deal with case when list of ICAT field names are found #265
Browse files Browse the repository at this point in the history
  • Loading branch information
VKTB committed Jan 17, 2022
1 parent ce9e2af commit 956a902
Showing 1 changed file with 24 additions and 7 deletions.
31 changes: 24 additions & 7 deletions datagateway_api/src/search_api/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,27 +38,44 @@ def from_icat(cls, icat_data): # noqa: B902, N805
panosc_entity_name, icat_field_name = mappings.get_icat_mapping(
cls.__name__, field_alias,
)
try:
field_value = _get_icat_field_value(icat_field_name, icat_data)
except KeyError:

if not isinstance(icat_field_name, list):
icat_field_name = [icat_field_name]

field_value = None
for field_name in icat_field_name:
try:
value = _get_icat_field_value(field_name, icat_data)
if value:
field_value = value
break
except KeyError:
continue

if not field_value:
continue

if panosc_entity_name != cls.__name__:
# If we are here, it means that the field references another model so we
# have to get hold of its class definition and call its `from_icat` method
# to create an instance of itself with the ICAT data provided. Doing this
# allows for recursion.
data = icat_data[icat_field_name]
data = field_value
if not isinstance(data, list):
data = [data]

# Get the class of the referenced model
panosc_model_attr = getattr(sys.modules[__name__], panosc_entity_name)
field_value = [panosc_model_attr.from_icat(d) for d in data]

field_type = cls.__fields__[field].outer_type_._name
if field_type != "List":
field_value = field_value[0]
field_outer_type = cls.__fields__[field].outer_type_
if (
not hasattr(field_outer_type, "_name")
or field_outer_type._name != "List"
) and isinstance(field_value, list):
# If the field does not hold list of values but `field_value`
# is a list, then just get its first element
field_value = field_value[0]

model_data[field_alias] = field_value

Expand Down

0 comments on commit 956a902

Please sign in to comment.