user2
user2

Reputation: 53

Blog count in django

I am trying to get the count of blogs by an author in views.py - author_blog_count but it is giving incorrect value. What can be the correct way of doing it?

models.py:

class Blog(models.Model):

    author  = models.ForeignKey(User, on_delete = models.CASCADE, related_name='blogger')
    created_date  = models.DateTimeField(default=timezone.now)
    published_date  = models.DateTimeField(blank=True, null=True)
    title  = models.CharField(max_length=100)

    def __str__(self):
        return self.title

views.py:

def get_queryset(self):
        return (Blog.objects.filter(published_date__lte=timezone.now())
                            .order_by('-published_date')
                            .annotate(
                                  author_blog_count=Count('author__blogger'),
                                  author_total_likes = Count('author__blogs__likes')
                                     )
                            .annotate(sum = (F('author_blog_count')+F('author_total_likes'))))

HTML:

  {% for blog in blog_list %}
      <div class="container" id ="main-cont">
         <div class="blog" id ="blog_cont">
            <a href="{% url 'blog_detail' pk=blog.pk %}" {{ blog.title }}</a> 
             {{ blog.description}}<br>{{blog.sum}}
              <br><br>
             <form method = "blog">
                   {% csrf_token %}
                   {{form}}
             </form>
             <a href="{% url 'blog_detail' pk=blog.pk %}"></a></div></div>

Error:

Reverse for blog_detail with keyword arguments {'pk': ''} not found. 1 pattern(s) tried: ['blog/blog/(?P<pk>\\d+)$']

Upvotes: 0

Views: 192

Answers (1)

JPG
JPG

Reputation: 88459

Try this,

def get_queryset(self):
    return Blog.objects.filter(...you filter).values('author').annotate(blog_count=Count('id')).order_by('author')<br><br>

Equivalant SQL statement :

SELECT COUNT(id) as blog_count, author
FROM Blog
GROUP BY author order by author;

Upvotes: 1

Related Questions