<commit_before>from django.core.cache import cache
from django.db.models import Manager, Sum
from django.db.models.aggregates import Count
from django.db.models.query import RawQuerySet
from kolibri.content.models import AssessmentMetaData, ChannelMetadata, ContentNode, File, Language
from le_utils.constants import content_kinds
from rest_framework import serializers


class ChannelMetadataSerializer(serializers.ModelSerializer):
    root = serializers.PrimaryKeyRelatedField(read_only=True)

    def to_representation(self, instance):
        value = super(ChannelMetadataSerializer, self).to_representation(instance)

        # if it has the file_size flag add extra file_size information
        if 'request' in self.context and self.context['request'].GET.get('file_sizes', False):
            file_summary = instance.root.get_descendants().prefetch_related('files__local_file').aggregate(
                total_file_size=Sum('files__local_file__file_size'),
                total_files=Count('files__local_file__file_size')
            )
            value.update(file_summary)
        return value
<commit_msg>Add resource count to ChannelMDSerializer<commit_after>from django.core.cache import cache
from django.db.models import Manager, Sum
from django.db.models.aggregates import Count
from django.db.models.query import RawQuerySet
from kolibri.content.models import AssessmentMetaData, ChannelMetadata, ContentNode, File, Language
from le_utils.constants import content_kinds
from rest_framework import serializers


class ChannelMetadataSerializer(serializers.ModelSerializer):
    root = serializers.PrimaryKeyRelatedField(read_only=True)

    def to_representation(self, instance):
        value = super(ChannelMetadataSerializer, self).to_representation(instance)

        # if it has the file_size flag add extra file_size information
        if 'request' in self.context and self.context['request'].GET.get('file_sizes', False):
            descendants = instance.root.get_descendants()
            total_resources = descendants.exclude(kind=content_kinds.TOPIC).count()
            channel_summary = descendants.prefetch_related('files__local_file').aggregate(
                total_file_size=Sum('files__local_file__file_size'),
                total_files=Count('files__local_file__file_size')
            )
            value.update({"total_resources": total_resources})
            value.update(channel_summary)
        return value

{'fraction_non_alphanumeric': 0.07651607651607652, 'fraction_numerical': 0.0, 'mean_word_length': 4.218683651804671, 'pattern_counts': {'":': 1, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '219822', 'n_tokens_mistral': 646, 'n_tokens_neox': 624, 'n_words': 144}