Django 注释计数并不总是有效 return 1

Django annotate count doesn't work always return 1

我的模特:

class PicKeyword(models.Model):
    """chat context collection

    """
    keyword = models.TextField(blank=True, null=True)

我的过滤器:

from django.db.models import Count
PicKeyword.objects.annotate(Count('keyword'))[0].keyword__count

结果总是得到1

就像:

print(PicKeyword.objects.filter(keyword='hi').count()

显示: 3

PicKeyword.objects.filter(keyword='hi').annotate(Count('keyword'))[0].keyword__count

显示: 1

是因为我使用了sqllite还是我的关键字类型是Textfield?

以下将显示确切的计数:

PicKeyword.objects.annotate(Count('keyword')).count()

您尝试在此处注释关键字计数的方式, PicKeyword.objects.annotate(Count('keyword'))[0].keyword__count
只有当你想总结多个对象之间的关系时才有效。因为,您没有任何与 keyword 字段相关的对象,所以输出始终为 1(它自己的实例)

正如 queryset.annotate 的 API 文档所述,

Annotates each object in the QuerySet with the provided list of query expressions. An expression may be a simple value, a reference to a field on the model (or any related models), or an aggregate expression (averages, sums, etc.) that has been computed over the objects that are related to the objects in the QuerySet.

Blog Model reference 对于 Queryset.annotate 示例

最后,如果对象之间没有关系,并且您的目标只是获取 PicKeyword 模型中对象的数量,那么@samba 和@Willem 的答案是正确的。

我遇到了完全相同的问题,none 的答案对我有用。 我能够使用以下语法使其工作,仅传递 1 个字段作为值(对我有用,因为我试图找出重复项):

dups = PicKeyword.objects.values('keyword').annotate(Count('keyword')).filter(keyword__count__gt=1)

以下 returns 始终是空查询集,不应:

dups = PicKeyword.objects.values('keyword','id').annotate(Count('keyword')).filter(keyword__count__gt=1)

希望对你有帮助