From 8aab3ffc3ba9e58b756364d7970672b7ae889f40 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20L=2E=20Redrejo=20Rodr=C3=ADguez?= Date: Fri, 13 Dec 2024 19:31:14 +0100 Subject: [PATCH] Add methods to calculate ordered categories and grade_levels --- kolibri/core/content/utils/annotation.py | 34 ++++++++++++++++++++++++ 1 file changed, 34 insertions(+) diff --git a/kolibri/core/content/utils/annotation.py b/kolibri/core/content/utils/annotation.py index af487d38518..a9cba7f146e 100644 --- a/kolibri/core/content/utils/annotation.py +++ b/kolibri/core/content/utils/annotation.py @@ -774,6 +774,8 @@ def set_channel_metadata_fields(channel_id, public=None): calculate_published_size(channel) calculate_total_resource_count(channel) calculate_included_languages(channel) + calculate_ordered_categories(channel) + calculate_ordered_grade_levels(channel) calculate_next_order(channel) if public is not None: @@ -811,6 +813,38 @@ def calculate_total_resource_count(channel): channel.save() +def _calculate_ordered_field_values(channel, field_name): + content_nodes = ContentNode.objects.filter( + channel_id=channel.id, available=True + ).exclude(**{field_name: None}) + all_values = [] + for node in content_nodes.values_list(field_name, flat=True): + if node: # just in case some field is an empty string + all_values.extend(node.split(",")) + + value_counts = {} + for value in all_values: + value_counts[value] = value_counts.get(value, 0) + 1 + + return sorted(value_counts.keys(), key=lambda x: value_counts[x], reverse=True) + + +def calculate_ordered_categories(channel): + ordered_categories = _calculate_ordered_field_values(channel, "categories") + channel.included_categories = ( + ",".join(ordered_categories) if ordered_categories else None + ) + channel.save() + + +def calculate_ordered_grade_levels(channel): + ordered_grade_levels = _calculate_ordered_field_values(channel, "grade_levels") + channel.included_grade_levels = ( + ",".join(ordered_grade_levels) if ordered_grade_levels else None + ) + channel.save() + + def calculate_included_languages(channel): content_nodes = ContentNode.objects.filter( channel_id=channel.id, available=True