django的博客数量

时间:2018-07-07 02:09:56

标签: python django django-queryset

我正在尝试获取views.py-author_blog_count中作者的博客数量,但它的值不正确。正确的方法是什么?

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>

错误:

  

找不到blog_detail的反向关键字,关键字参数为{'pk': ''}。尝试了1个模式:['blog/blog/(?P<pk>\\d+)$']

2 个答案:

答案 0 :(得分:1)

尝试一下,

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

等效的SQL语句:

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

答案 1 :(得分:0)

我强烈建议使用Django Debug Toolbar。您可以看到生成的 SQL 查询。如果您可以在此处发布,我们可以提供更多帮助。 如果没有,请选中此tutorial

PS: 我没有足够的声誉来发表评论。