Skip to content

Commit

Permalink
#223: Allow data from related entities from distinct filters to be n…
Browse files Browse the repository at this point in the history
…ested correctly

- This is using the functions moved to common.helpers in the previous commit
  • Loading branch information
MRichards99 committed May 11, 2021
1 parent e67ee26 commit dec86b7
Showing 1 changed file with 11 additions and 3 deletions.
14 changes: 11 additions & 3 deletions datagateway_api/common/database/helpers.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
from abc import ABC, abstractmethod
from datagateway_api.common.helpers import map_distinct_attributes_to_results
import datetime
from functools import wraps
import logging
Expand All @@ -7,6 +8,7 @@
from sqlalchemy.orm import aliased

from datagateway_api.common.database.filters import (
DatabaseDistinctFieldFilter,
DatabaseIncludeFilter as IncludeFilter,
DatabaseWhereFilter as WhereFilter,
)
Expand Down Expand Up @@ -278,7 +280,7 @@ def get_filtered_read_query_results(filter_handler, filters, query):
filter_handler.apply_filters(query)
results = query.get_all_results()
if query.is_distinct_fields_query:
return _get_distinct_fields_as_dicts(results)
return _get_distinct_fields_as_dicts(filters, results)
if query.include_related_entities:
return _get_results_with_include(filters, results)
return list(map(lambda x: x.to_dict(), results))
Expand All @@ -298,18 +300,24 @@ def _get_results_with_include(filters, results):
return [x.to_nested_dict(query_filter.included_filters) for x in results]


def _get_distinct_fields_as_dicts(results):
def _get_distinct_fields_as_dicts(filters, results):
"""
Given a list of column results return a list of dictionaries where each column name
is the key and the column value is the dictionary key value
:param results: A list of sql alchemy result objects
:return: A list of dictionary representations of the sqlalchemy result objects
"""
distinct_fields = []
for query_filter in filters:
if type(query_filter) is DatabaseDistinctFieldFilter:
distinct_fields.extend(query_filter.fields)

dictionaries = []
for result in results:
dictionary = {k: getattr(result, k) for k in result.keys()}
dictionary = map_distinct_attributes_to_results(distinct_fields, result)
dictionaries.append(dictionary)

return dictionaries


Expand Down

0 comments on commit dec86b7

Please sign in to comment.