Python 带计数的外键引用
我正在尝试获取外键(作者)的计数,以获取用户创建的博客总数。但它显示的总数不正确。是否有人可以帮助您获取带有count的外键引用。谢谢 models.pyPython 带计数的外键引用,python,django,Python,Django,我正在尝试获取外键(作者)的计数,以获取用户创建的博客总数。但它显示的总数不正确。是否有人可以帮助您获取带有count的外键引用。谢谢 models.py class Blog(models.Model): author = models.ForeignKey(User, on_delete = models.CASCADE, related_name='blogs') created_date = models.DateTimeField(default=timez
class Blog(models.Model):
author = models.ForeignKey(User, on_delete = models.CASCADE, related_name='blogs')
created_date = models.DateTimeField(default=timezone.now)
def total_likes_received(user):
return user.blogs.aggregate(total_likes=Count('likes'))
views.py
def get_queryset(self):
return (Blog.objects.filter(date__lte=timezone.now())
.order_by('-date')
.annotate(
author_total_likes = Count('author__blogs__likes'),
author_total_blogs = Count('author__blogs')
)
您只需添加此项,并在调用该方法时传递用户id
class Blog(models.Model):
author = models.ForeignKey(User, on_delete=models.CASCADE,
related_name='blogs')
created_date = models.DateTimeField(default=timezone.now)
def total_likes_received(user):
return self.__class__.objects.filter(author_id=user).count()
您将获得与id=1的User
相关的Blog
实例的计数
更新
aggregation = Blog.objects.values('blog').annotate(count=Count('author'))
你为什么用Blogger类而不是Blog?哦,那是个打字错误。更正了。我想获得所有作者的计数,并根据博客作者将其显示在views.py中?我已尝试返回(Blog.objects.filter(date\u lte=timezone.now()).order\u by('-date')。注释(author\u total\u blogs=Count('author'))但是它没有给出正确的数字您可以在任何地方尝试它您可以显示完整的视图
?您打算如何显示它?我在那里有它。我想在author\u total\u博客中获取它。我已经尝试了您的代码,它给出的错误是“blog”不是一个字段
aggregation = Blog.objects.values('blog').annotate(count=Count('author'))