user
user

Reputation: 317

Foreign key reference with count

I am trying to get the count of foreign key(author) in order to get the count of total blogs made by a user. But it is showing the incorrect total. Can someone help on how to get the foreign key reference with count. Thanks.

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

Upvotes: 1

Views: 57

Answers (2)

JPG
JPG

Reputation: 88499

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

You will get the count of Blog instances related to User with id=1
Update

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

Upvotes: 1

Edwin De Los Santos
Edwin De Los Santos

Reputation: 18

You just have to add this and pass the user id when the method is called.

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

Upvotes: 0

Related Questions