Count elements in Django

Question:

I am learning Django. I have a question about counting elements from tables.

class Opinion(models.Model):
    id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False)
    users = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True)
    books = models.ForeignKey(Book, on_delete=models.SET_NULL, null=True, blank=True)
    created = models.DateTimeField(auto_now_add=True)
    rate = models.IntegerField()
    description = models.TextField()

    def __str__(self):
        return self.user_id.username + ' ' + self.book_id.title 

My table Opinion is in relationship with built-in table User.
I am wondering how can I count how many opinions each user has added?

I would like to show information about users and the amount of opinions they have added on my website.

Asked By: gregory_000

||

Answers:

You can .annotate(…) [Django-doc] with:

from django.db.models import Count

User.objects.annotate(number_of_opinions=Count('opinion'))

The User objects that arise from this QuerySet will have an extra attribute .number_of_opinions.


Note: It is normally better to make use of the settings.AUTH_USER_MODEL [Django-doc] to refer to the user model, than to use the User model [Django-doc] directly. For more information you can see the referencing the User model section of the documentation.

Answered By: Willem Van Onsem
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.