Py学习  »  Django

django-是否可以在count()内执行queryset

Jack • 7 年前 • 2387 次点击  

我有下列型号

class Client(models.Model):
    ...

class Request(models.Model):
    ...
    client = models.ForeignKey(Client, on_delete=models.SET_NULL, null=True)
    completed = models.BooleanField()

我想得到一组客户端的所有已完成请求的计数。以下语句获取所有请求,但不检查请求是否已完成。

clients = Client.objects.filter(...).annotate(Count('request'))

我想要的是:

clients = Client.objects.filter(...).annotate(Count(request__completed=True))

我怎样才能做到这一点?

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/39683
文章 [ 2 ]  |  最新文章 7 年前
Kiran S youtube channel
Reply   •   1 楼
Kiran S youtube channel    8 年前
from django.db.models import Count
ModelName.objects.aggregate(Count('id'))

please check the ref for more

JPG
Reply   •   2 楼
JPG    8 年前

正如“红蟋蟀”所说,你可以得到 过滤计数 达金戈的 count() 方法为

Client.objects.filter(my_otherfilters..,request__completed=True).count()

这将返回 整数值 代表伯爵。


如果你想 QuerySet 以及 count ,

qs = Client.objects.filter(my_otherfilters..,request__completed=True) # the "qs" will get the querysets
qs_count = qs.count() # "qs_count" will return the count