在Django中将默认计数注释为0(零)

2024-04-23 16:50:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我在views.py中有以下代码

class UserPostListView(ListView):
    model = Post
    template_name = 'blog/user_posts.html'
    context_object_name='posts'
    paginate_by = 4

    def get_queryset(self):
        user = get_object_or_404(User, username=self.kwargs.get('username'))
        return Post.objects.filter(author=user).order_by('-date_posted')

    def get_context_data(self, **kwargs):
        context = super(UserPostListView, self).get_context_data(**kwargs)
        user = get_object_or_404(User, username=self.kwargs.get('username'))
        context['postuser'] = Post.objects.filter(author=user).order_by('-date_posted')[:1]
        context['posts'] = Post.objects.filter(author=user).order_by('-date_posted')
        context['postns'] = {d['status__count'] for d in Post.objects.filter(author=user,status="NOT STARTED").order_by('status').values('status').annotate(Count('status'))}

html

{% for post in postns %}
    <div class="col-auto col-ns-st padding-col-st"><span class="vertical-span"><i class="fa fa-circle color-ico-st"></i>&nbsp;{{ post }}</span></div>
{% endfor %}

型号.py

class Post(models.Model):
    NS= 'NOT STARTED'
    STATUS_CHOICES = (
        ('NOT STARTED','NOT STARTED'),
        ('IN PROGRESS','IN PROGRESS'),
        ('COMPLETE','COMPLETE'),
        )
status=models.CharField(max_length=40, choices = STATUS_CHOICES,default=NS)

当我有一篇带有图例“NOT STARTED”的帖子时,代码正在运行并计算帖子的数量,但如果没有帖子,则不会显示任何值

如果没有发布数据,如何将代码默认为“0”


Tags: selfgetbyobjectsstatuscontextusernamenot
1条回答
网友
1楼 · 发布于 2024-04-23 16:50:39

由于您对状态进行筛选,因此在此处使用^{} [Django-doc]似乎更有意义:

context['postns'] = Post.objects.filter(
    author=user,status="NOT STARTED"
).count()

然后,您可以使用以下方法渲染此内容:

<div class="col-auto col-ns-st padding-col-st"><span class="vertical-span"><i class="fa fa-circle color-ico-st"></i>&nbsp;{{ postns }}</span></div>

相关问题 更多 >