Подсчет элементов в Django

Я изучаю Django. У меня есть вопрос о подсчете элементов из таблиц.

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 

Моя таблица Opinion находится во взаимосвязи со встроенной таблицей User. Мне интересно, как я могу подсчитать, сколько мнений добавил каждый пользователь?

Я хотел бы показать информацию о пользователях и количестве мнений, которые они добавили на мой сайт.

Спасибо за помощь.

Вы можете .annotate(…) [Django-doc] с:

from django.db.models import Count

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

Объекты User, возникающие в результате этого QuerySet будут иметь дополнительный атрибут .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.

Вернуться на верх