我正在学习 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 theUser
model [Django-doc] directly. For more information you can see the referencing theUser
model section of the documentation.
关于python - Django 中的元素计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73591251/