如何从Django中选择字段过滤的数据库中计算对象数?

2024-06-01 20:20:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我有Porumbei模型,它有性别字段。在模板中,我必须呈现每个性别的Porumbei数量。例如:男=x波伦贝,女=y波伦贝,未知=z波伦贝

我的模型

class Porumbei(models.Model):
    SEXE = [
        ('Mascul', 'Mascul'),
        ('Femelă', 'Femelă'),
        ('Pui', 'Pui')
    ]
    ...
    gender = models.CharField(max_length=6, choices=SEXE, db_index=True)
    ...

我总共有:

total = Porumbei.objects.count()

以下是我现在的情况:

@staticmethod
def masculi(crescator=None):
    """ Numarul de masculi din sistem """
    mascul = Porumbei.objects.filter(gender="Mascul", is_active=True, crescator=crescator)
    return len(mascul)

@staticmethod
def femele(crescator=None):
    """ Numarul de femele din sistem """
    femela = Porumbei.objects.filter(gender="Femelă", is_active=True, crescator=crescator)
    return len(femela)

@staticmethod
def pui(crescator=None):
    """ Numarul de pui din sistem """
    pui = Porumbei.objects.filter(gender="Pui", is_active=True, crescator=crescator)
    return len(pui)

这些函数满足了我的需求,但从我的角度来看,它们并没有得到很好的优化。正如我在django调试工具栏中看到的,这将在三个类似的查询中结束。我的问题是,如何在一个查询中获得每个性别的数字。是否可以使用其他方法,或者可以优化此函数以在数据库中执行单个查询?我必须提到,对于每个性别的数字,必须进行算术运算。例如,每个性别占总数的多少。 提前谢谢


Tags: nonetrueobjectsdefdegender性别pui
1条回答
网友
1楼 · 发布于 2024-06-01 20:20:18

您可以使用values()annotate()gender字段上运行GROUP BY,然后获取计数

from django.db.models import Count

gender_count = Porumbei.objects.values('gender').annotate(count=Count('gender')).order_by()

order_by()在这里是一个可选子句,但是当为Model定义默认顺序时,应该添加它。从docs

Fields that are mentioned in the order_by() part of a queryset (or which are used in the default ordering on a model) are used when selecting the output data, even if they are not otherwise specified in the values() call. These extra fields are used to group “like” results together and they can make otherwise identical result rows appear to be separate. This shows up, particularly, when counting things.

在末尾添加order_by()将清除任何默认顺序

How can I render this into template?

gender_count字典将包含gender值作为键,相应的计数作为值

要在模板中呈现,gender_count,可以在dict上迭代

{% for gender, count in gender_count.items %} 
    <p>{{gender}}: {{count}}</p>
{% endfor %}

相关问题 更多 >