带计数的外键参考

时间:2018-07-05 12:38:50

标签: python django

我试图获取外键(作者)的数量,以获取用户制作的博客总数。但是它显示了不正确的总数。有人可以帮忙如何获得带有计数的外键引用。谢谢。

models.py

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')
                                             )

2 个答案:

答案 0 :(得分:1)

user_id=1
count = Blog.objects.filter(author_id=user_id).count()

您将获得与BlogUser相关的 id=1 个实例的数量
更新

aggregation = Blog.objects.values('blog').annotate(count=Count('author'))

答案 1 :(得分:0)

您只需添加此名称并在调用该方法时传递用户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()