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

The following are 25 code examples of django.db.models.aggregates.Count(). 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 also want to check out all available functions/classes of the module django.db.models.aggregates , or try the search function .
Example #1
Source File: blog_tags.py    From django_blog with 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 #2
Source File: 0197_remove_duplicate_physical_interfaces.py    From maas with GNU Affero General Public License v3.0 5 votes vote down vote up
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 #3
Source File: sitemaps.py    From izone with 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 #4
Source File: sitemaps.py    From izone with 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 #5
Source File: blog_tags.py    From izone with 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 #6
Source File: blog_tags.py    From izone with 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 #7
Source File: tool_tags.py    From izone with 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 #8
Source File: policy_points_earned.py    From bridge-adaptivity with 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 #9
Source File: base.py    From bridge-adaptivity with 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 #10
Source File: blog_extras.py    From HelloDjango-blog-tutorial with 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 #11
Source File: blog_extras.py    From HelloDjango-blog-tutorial with 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 #12
Source File: comment_tags.py    From django_blog with 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 #13
Source File: query.py    From GTDWeb with 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 #14
Source File: blog_tags.py    From django_blog with 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 #15
Source File: query.py    From python2017 with 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 #16
Source File: sitemaps.py    From blog with 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 #17
Source File: sitemaps.py    From blog with 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 #18
Source File: blog_tags.py    From blog with 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 #19
Source File: query.py    From openhgsenti with 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 #20
Source File: query.py    From python with 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 #21
Source File: query.py    From Hands-On-Application-Development-with-PyCharm with 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 #22
Source File: discussion_tags.py    From BookForum with 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 #23
Source File: views.py    From BookForum with 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 #24
Source File: query.py    From bioforum with 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 #25
Source File: 0190_bmc_clean_duplicates.py    From maas with GNU Affero General Public License v3.0 4 votes vote down vote up
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)