Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Django对象不计数_Django_Python 3.x_Django Models_Django Templates - Fatal编程技术网

Django对象不计数

Django对象不计数,django,python-3.x,django-models,django-templates,Django,Python 3.x,Django Models,Django Templates,当用户添加项目时,项目的数量应该显示在仪表板中,但我的代码不计算,但是它在这里只显示了零,这是我迄今为止尝试过的 视图.py class ItemListView(LoginRequiredMixin, ListView): model = Item template_name = 'item/items.html' context_object_name = 'items' ordering = ['-created_at', '-updated_at']

当用户添加项目时,项目的数量应该显示在仪表板中,但我的代码不计算,但是它在这里只显示了零,这是我迄今为止尝试过的

视图.py

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 %}

可以在项目模型中定义属性:

class Item(models.Model):

    title = models.CharField(max_length=100)

    @property
    def count(self):
        self.__class__.objects.filter(author=self.request.user).count()

不需要更改模板。此外,视图中的queryset不再需要

您已经在模板中调用了{{items.count}}。我对这个案子的看法。当{items.count}出现在模板中时,@property将被调用为
\uuuuu class\uuuu
?你把它加入模型?哇,太棒了@shafik很抱歉,我让您费心了一段时间,它终于开始工作了,但有一件事我想知道,物品计数只是仪表板的一个功能。如果我想添加其他功能,是否应该向仪表板添加更多URL?否。您可以使用
获取上下文\u数据
。研究这个。这可能对你有帮助。另一个url不能解决您的问题