Skip to content

Commit

Permalink
#119: Edit entity conversion to work with most camelCase attribute n…
Browse files Browse the repository at this point in the history
…ames

- This doesn't work with foreign key attribute keys yet - e.g. "DATACOLLECTION_ID" will be changed to "datacollectionid" and this doesn't match the variable names in the entities
  • Loading branch information
MRichards99 committed Jan 25, 2021
1 parent 279681a commit 0d0c5d0
Showing 1 changed file with 15 additions and 3 deletions.
18 changes: 15 additions & 3 deletions datagateway_api/common/database/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -84,8 +84,20 @@ def to_dict(self):
"""
dictionary = {}
for column in self.__table__.columns:
attribute = getattr(self, column.name)
dictionary[column.name] = self._make_serializable(attribute)
camel_case_column_name = None
attribute = None

# Case insensitive alternative to getattr() - needed because column names
# are defined in SNAKE_CASE, class column variables named using camelCase to
# match Python ICAT backend
for a in dir(self):
if a.lower() == column.name.replace("_", "").lower():
attribute = getattr(self, a)
camel_case_column_name = a

if camel_case_column_name is not None and attribute is not None:
dictionary[camel_case_column_name] = self._make_serializable(attribute)

return dictionary

def _make_serializable(self, field):
Expand Down Expand Up @@ -183,7 +195,7 @@ def update_from_dict(self, dictionary):
:returns: The updated dict
"""
for key in dictionary:
setattr(self, key.upper(), dictionary[key])
setattr(self, key, dictionary[key])
return self.to_dict()


Expand Down

0 comments on commit 0d0c5d0

Please sign in to comment.