Search code examples
pythondjangoannotate

Django annotate count doesn't work always return 1


My models:

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

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

Myfilter:

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

The result always get 1

just like:

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

show: 3

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

show: 1

Is it because I use sqllite or my keyword type is Textfield?


Solution

  • The way you are trying to annotate the count of keywords here, PicKeyword.objects.annotate(Count('keyword'))[0].keyword__count
    only works when you want to summarize the relationship between multiple objects. Since, you do not have any related objects to the keyword field the output is always 1 (it's own instance)

    As the API docs for queryset.annotate states,

    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 for the Queryset.annotate example

    Finally, If there are no relationships among objects and your aim is to just get the count of objects in your PicKeyword Model, the answers from @samba and @Willem are correct.