Skip to content

Commit

Permalink
#119: Set response body keys based on field name rather than table name
Browse files Browse the repository at this point in the history
- This change also allows related entities to be retrieved on with plural field name
- Related entities with a singular field name also typically have a foreign key attribute in the class. When an include filter is used in this situation, the included entity will be returned in the response body, rather than the foreign key. This had a better outcome than I thought it would've done :)
  • Loading branch information
MRichards99 committed Feb 1, 2021
1 parent b9e52d9 commit ce5e763
Showing 1 changed file with 11 additions and 11 deletions.
22 changes: 11 additions & 11 deletions datagateway_api/common/database/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -114,17 +114,17 @@ def _nest_dictionary_include(self, dictionary, include):
"""
related_entity = self.get_related_entity(list(include)[0])
if not isinstance(related_entity, InstrumentedList):
dictionary[related_entity.__tablename__] = related_entity.to_nested_dict(
include[list(include)[0]],
)
dictionary[
related_entity.__singularfieldname__
] = related_entity.to_nested_dict(include[list(include)[0]])
else:
for entity in related_entity:
if entity.__tablename__ in dictionary.keys():
dictionary[entity.__tablename__].append(
if entity.__pluralfieldname__ in dictionary.keys():
dictionary[entity.__pluralfieldname__].append(
entity.to_nested_dict(include[list(include)[0]]),
)
else:
dictionary[entity.__tablename__] = [
dictionary[entity.__pluralfieldname__] = [
entity.to_nested_dict(include[list(include)[0]]),
]

Expand All @@ -138,13 +138,13 @@ def _nest_string_include(self, dictionary, include):
"""
related_entity = self.get_related_entity(include)
if not isinstance(related_entity, InstrumentedList):
dictionary[related_entity.__tablename__] = related_entity.to_dict()
dictionary[related_entity.__singularfieldname__] = related_entity.to_dict()
else:
for entity in related_entity:
if entity.__tablename__ in dictionary.keys():
dictionary[entity.__tablename__].append(entity.to_dict())
if entity.__pluralfieldname__ in dictionary.keys():
dictionary[entity.__pluralfieldname__].append(entity.to_dict())
else:
dictionary[entity.__tablename__] = [entity.to_dict()]
dictionary[entity.__pluralfieldname__] = [entity.to_dict()]

def get_related_entity(self, entity):
"""
Expand All @@ -153,7 +153,7 @@ def get_related_entity(self, entity):
:return: The entity
"""
try:
return getattr(self, entity)
return getattr(self, entity if entity[-1] == "s" else entity.upper())
except AttributeError:
raise FilterError(f" No related entity: {entity}")

Expand Down

0 comments on commit ce5e763

Please sign in to comment.