当用户添加项目时,项目数量应该出现在仪表板中,但我的代码不计算,但是这里只显示零到目前为止我尝试过的内容。
views.朋友
class ItemListView(LoginRequiredMixin, ListView):
model = Item
template_name = 'item/items.html'
context_object_name = 'items'
ordering = ['-created_at', '-updated_at']
def get_queryset(self):
return super(ItemListView, self).get_queryset().filter(author=self.request.user)
class ItemCountView(LoginRequiredMixin, ListView):
model = Item
template_name = 'dashboard/dash.html'
context_object_name = 'items'
def get_queryset(self):
return Item.objects.filter(author=self.request.user)
在模板dash.html中
当它是{{ items.count }}
它不算,但如果{{ items|length }}
它显示零。请告诉我我犯错的地方。
在queryset中使用count()
def get_queryset(self):
return Item.objects.filter(author=self.request.user).count()
然后在模板中使用{{ items }}
更新:
class ItemListView(LoginRequiredMixin, View):
template_name = 'item/items.html'
login_url = 'accounts/login/'
def get(self, request, *args, **kwargs):
total_item = Item.objects.filter(author=self.request.user).count()
context = {'total_item': total_item}
return render(request, self.template_name, context)
在模板中使用{{ total_item }}
更新2:
class ItemCountView(LoginRequiredMixin, ListView):
model = Item
template_name = 'dashboard/dash.html'
context_object_name = 'items'
def get_queryset(self):
return Item.objects.all().values('item_name').annotate(total=Count('item_name'))
然后在模板中使用
{% for item in items %}
{{ item.item_name }} {{ item.total }}
{% endfor %}
您可以在Item模型中定义属性:
class Item(models.Model):
title = models.CharField(max_length=100)
@property
def count(self):
self.__class__.objects.filter(author=self.request.user).count()
无需更改模板。此外,不再需要查看中的查询集