Python django.db.models.aggregates.Count() Examples

The following are 25 code examples for showing how to use django.db.models.aggregates.Count(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.

You may check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module django.db.models.aggregates , or try the search function .

Example 1
Project: GTDWeb   Author: lanbing510   File: query.py    License: GNU General Public License v2.0 5 votes vote down vote up
def get_count(self, using):
        """
        Performs a COUNT() query using the current filter constraints.
        """
        obj = self.clone()
        obj.add_annotation(Count('*'), alias='__count', is_summary=True)
        number = obj.get_aggregation(using, ['__count'])['__count']
        if number is None:
            number = 0
        return number 
Example 2
Project: bioforum   Author: reBiocoder   File: query.py    License: MIT License 5 votes vote down vote up
def get_count(self, using):
        """
        Perform a COUNT() query using the current filter constraints.
        """
        obj = self.clone()
        obj.add_annotation(Count('*'), alias='__count', is_summary=True)
        number = obj.get_aggregation(using, ['__count'])['__count']
        if number is None:
            number = 0
        return number 
Example 3
Project: BookForum   Author: Arianxx   File: views.py    License: MIT License 5 votes vote down vote up
def all_hot_dicussions(request):
    discussions = Discuss.objects.annotate(reply_num=Count('replys')).all()[:10]
    discussions = sorted(discussions, key=lambda x: x.reply_num, reverse=True)

    context = {
        'discussions': discussions,
    }
    return render(request, 'Discussion/hot_discussions.html', context=context) 
Example 4
Project: BookForum   Author: Arianxx   File: discussion_tags.py    License: MIT License 5 votes vote down vote up
def get_hot_discussions(num=5):
    """
    得到指定数量的热门讨论

    :param num: 想要得到的讨论数量
    :return: Discuss模型的实例列表
    """
    discussions = Discuss.objects.annotate(reply_num=Count('replys')).all()
    discussions = sorted(discussions, key=lambda x: x.reply_num, reverse=True)
    return discussions[:num] 
Example 5
Project: Hands-On-Application-Development-with-PyCharm   Author: PacktPublishing   File: query.py    License: MIT License 5 votes vote down vote up
def get_count(self, using):
        """
        Perform a COUNT() query using the current filter constraints.
        """
        obj = self.clone()
        obj.add_annotation(Count('*'), alias='__count', is_summary=True)
        number = obj.get_aggregation(using, ['__count'])['__count']
        if number is None:
            number = 0
        return number 
Example 6
Project: python   Author: Yeah-Kun   File: query.py    License: Apache License 2.0 5 votes vote down vote up
def get_count(self, using):
        """
        Performs a COUNT() query using the current filter constraints.
        """
        obj = self.clone()
        obj.add_annotation(Count('*'), alias='__count', is_summary=True)
        number = obj.get_aggregation(using, ['__count'])['__count']
        if number is None:
            number = 0
        return number 
Example 7
Project: openhgsenti   Author: drexly   File: query.py    License: Apache License 2.0 5 votes vote down vote up
def get_count(self, using):
        """
        Performs a COUNT() query using the current filter constraints.
        """
        obj = self.clone()
        obj.add_annotation(Count('*'), alias='__count', is_summary=True)
        number = obj.get_aggregation(using, ['__count'])['__count']
        if number is None:
            number = 0
        return number 
Example 8
Project: blog   Author: stormsha   File: blog_tags.py    License: Apache License 2.0 5 votes vote down vote up
def get_tag_list():
    """返回标签列表"""
    return Tag.objects.annotate(total_num=Count('article')).filter(total_num__gt=0)


# 返回活跃的友情链接查询集 
Example 9
Project: blog   Author: stormsha   File: sitemaps.py    License: Apache License 2.0 5 votes vote down vote up
def items(self):
        return Category.objects.annotate(total_num=Count('article')).filter(total_num__gt=0) 
Example 10
Project: blog   Author: stormsha   File: sitemaps.py    License: Apache License 2.0 5 votes vote down vote up
def items(self):
        return Tag.objects.annotate(total_num=Count('article')).filter(total_num__gt=0) 
Example 11
Project: python2017   Author: bpgc-cte   File: query.py    License: MIT License 5 votes vote down vote up
def get_count(self, using):
        """
        Performs a COUNT() query using the current filter constraints.
        """
        obj = self.clone()
        obj.add_annotation(Count('*'), alias='__count', is_summary=True)
        number = obj.get_aggregation(using, ['__count'])['__count']
        if number is None:
            number = 0
        return number 
Example 12
Project: django_blog   Author: r26zhao   File: blog_tags.py    License: MIT License 5 votes vote down vote up
def get_category():
    category_list = Category.objects.annotate(post_num=Count('post')).order_by('-post_num')
    Category.objects.values()
    return category_list 
Example 13
Project: django_blog   Author: r26zhao   File: blog_tags.py    License: MIT License 5 votes vote down vote up
def get_tag():
    tag_list = Tag.objects.annotate(post_num=Count('post')).order_by('-post_num')
    return tag_list 
Example 14
Project: django_blog   Author: r26zhao   File: comment_tags.py    License: MIT License 5 votes vote down vote up
def get_comment_rank(num=5):
    app_model = settings.COMMENT_ENTRY_MODEL.split('.')
    Post = apps.get_model(*app_model)
    post_list = Post.objects.annotate(comment_num=Count('comment')).order_by('-comment_num')
    return post_list[:num] 
Example 15
Project: HelloDjango-blog-tutorial   Author: HelloGitHub-Team   File: blog_extras.py    License: GNU General Public License v3.0 5 votes vote down vote up
def show_categories(context):
    category_list = Category.objects.annotate(num_posts=Count('post')).filter(num_posts__gt=0)
    return {
        'category_list': category_list,
    } 
Example 16
Project: HelloDjango-blog-tutorial   Author: HelloGitHub-Team   File: blog_extras.py    License: GNU General Public License v3.0 5 votes vote down vote up
def show_tags(context):
    tag_list = Tag.objects.annotate(num_posts=Count('post')).filter(num_posts__gt=0)
    return {
        'tag_list': tag_list,
    } 
Example 17
Project: bridge-adaptivity   Author: harvard-vpal   File: base.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _get_points_earned_trials_count(self):
        """Get points earned and trials count from the sequence.

        :return tuple([trials_count, points_earned])
        """
        items_result = self.sequence.items.aggregate(
            points_earned=Sum('score'), trials_count=Count('score')
        )
        return items_result['trials_count'], items_result['points_earned'] 
Example 18
Project: bridge-adaptivity   Author: harvard-vpal   File: policy_points_earned.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _get_points_earned_trials_count(self):
        """Get points earned and trials count from the sequence.

        :return tuple([trials_count, points_earned])
        """
        # Note(idegtiarov) With the first non-problem activity in the sequence and default value of the threshold
        # item_result returns None, 0 which are not appropriate for the grade calculation method, valid default values
        # are provided to fix this issue.
        items_result = self.sequence.items.exclude(is_problem=False).aggregate(
            points_earned=Coalesce(Sum('score'), 0), trials_count=Greatest(Count('score'), 1)
        )
        return items_result['trials_count'], items_result['points_earned'] 
Example 19
Project: izone   Author: Hopetree   File: tool_tags.py    License: MIT License 5 votes vote down vote up
def get_toolcates():
    '''获取所有工具分类,只显示有工具的分类'''
    return ToolCategory.objects.annotate(total_num=Count('toollink')).filter(total_num__gt=0) 
Example 20
Project: izone   Author: Hopetree   File: blog_tags.py    License: MIT License 5 votes vote down vote up
def get_tag_list():
    '''返回标签列表'''
    return Tag.objects.annotate(total_num=Count('article')).filter(total_num__gt=0) 
Example 21
Project: izone   Author: Hopetree   File: blog_tags.py    License: MIT License 5 votes vote down vote up
def get_category_list():
    '''返回分类列表'''
    return Category.objects.annotate(total_num=Count('article')).filter(total_num__gt=0) 
Example 22
Project: izone   Author: Hopetree   File: sitemaps.py    License: MIT License 5 votes vote down vote up
def items(self):
        return Category.objects.annotate(total_num=Count('article')).filter(total_num__gt=0) 
Example 23
Project: izone   Author: Hopetree   File: sitemaps.py    License: MIT License 5 votes vote down vote up
def items(self):
        return Tag.objects.annotate(total_num=Count('article')).filter(total_num__gt=0) 
Example 24
def remove_duplicate_physical_interfaces(apps, schema_editor):
    Interface = apps.get_model("maasserver", "Interface")

    # Find duplicated physical interfaces and remove them, keeping only the
    # interface that has IP addresses or the latest physical interface.
    qs = Interface.objects.values("type", "mac_address")
    qs = qs.filter(type="physical")
    qs = qs.order_by()  # clear default ordering
    qs = qs.annotate(ids=ArrayAgg("id")).annotate(count=Count("id"))
    qs = qs.filter(count__gt=1)
    for entry in qs:
        nic_ids = list(sorted(entry["ids"]))
        has_ips = list(
            sorted(
                nic.id
                for nic in Interface.objects.filter(id__in=nic_ids)
                if nic.ip_addresses.all()
            )
        )
        if len(has_ips) == 0:
            # None of the physical interfaces have an IP address, remove
            # the older interfaces.
            Interface.objects.filter(id__in=nic_ids[:-1]).delete()
        elif len(has_ips) == 1:
            # Keep only the physical interface that has IP addresses.
            nic_ids.remove(has_ips[0])
            Interface.objects.filter(id__in=nic_ids).delete()
        else:
            # Remove those that have no IPs.
            no_ips = set(nic_ids) - set(has_ips)
            if no_ips:
                Interface.objects.filter(id__in=no_ips).delete()
            # Multiple have IP addresses. Remove the IP addresses from the
            # others and only keep the latest with IP addresses.
            for nic in Interface.objects.filter(id__in=has_ips[:-1]):
                nic.ip_addresses.all().delete()
                nic.delete() 
Example 25
def clean_bmcs(apps, schema_editor):
    BMC = apps.get_model("maasserver", "BMC")
    Node = apps.get_model("maasserver", "Node")

    # delete BMCs that are not linked to any node
    BMC.objects.exclude(
        id__in=Node.objects.values("bmc_id")
    ).distinct().delete()

    # find duplicated BMCs and remove them, moving nodes to the only one left
    # for each group
    bmc_ids_to_delete = []

    qs = BMC.objects.values("power_type", "power_parameters")
    qs = qs.exclude(power_type="manual")
    qs = qs.annotate(ids=ArrayAgg("id")).annotate(count=Count("id"))
    qs = qs.filter(count__gt=1)
    for entry in qs:
        bmc_ids = entry["ids"]
        bmc_id = bmc_ids.pop()
        Node.objects.filter(bmc_id__in=bmc_ids).update(bmc_id=bmc_id)
        bmc_ids_to_delete.extend(bmc_ids)

    if bmc_ids_to_delete:
        BMC.objects.filter(id__in=bmc_ids_to_delete).delete()

    # find non-chassis BMCs that are linked to multiple nodes.  Such cases are
    # not valid, so we unset the BCM for all nodes except one, so BMC
    # parameters (such as user/password) are not lost. Users will likely have
    # to fix those node manually anyway.
    qs = BMC.objects.values("id")
    qs = qs.filter(power_type__in=NON_CHASSIS_POWER_TYPES)
    qs = qs.annotate(node_ids=ArrayAgg("node"), node_count=Count("node"))
    qs = qs.filter(node_count__gt=1)
    node_ids_to_unset = []
    for entry in qs:
        node_ids = entry["node_ids"]
        node_ids.pop()  # keep one node with the original
        node_ids_to_unset.append(node_ids)

    if node_ids_to_unset:
        Node.objects.filter(id__in=node_ids_to_unset).update(bmc_id=None)