python - Django 中的元素计数

标签 python django django-models django-queryset django-annotate

我正在学习 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 

我的表意见与内置表用户有关系。 我想知道如何统计每个用户添加了多少意见?

我想显示有关用户的信息以及他们在我的网站上添加的意见数量。

最佳答案

您可以.annotate(…) [Django-doc]与:

from django.db.models import <b>Count</b>

User.objects.annotate(<b>number_of_opinions=Count('opinion')</b>)

从此 QuerySet 产生的 User 对象将具有一个额外的属性 .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.

关于python - Django 中的元素计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73591251/

相关文章:

python - Django 等价于 PHP 的表单值数组/关联数组

python - 通过 JSON 发送文件而不是上传到服务器,Django

python - 在 Python 中跟踪数据类型

python - 绘图中重叠的色阶

python - 如何将 "Day_Name Month Day_No. Time Year"转换为日期格式?

python - Tkinter 中真正的自定义字体

python - 将 Django 连接到 MongoLab 数据库

django - django 中给定用户的 message_set

python - Django 更新而不是插入新记录

django - 如何增加显示在 Django 模板中的年份范围?