Django 查询:另一个计数问题
你好,我似乎在 Django 中的计数方面遇到了一些问题。我有一个项目列表,仅显示其最新状态。所有这些状态为“已销毁”的物品均已被删除。这打印得很好。
status_items = models.StorageItem.objects.filter(client=client_id, itemstatushistory__isnull=False).distinct()
{% for item in status_items %}
{{item.itemstatushistory_set.latest|cut:"Destroyed"}}
{% endfor %}
但由于某种原因我无法计算。
status_items = models.StorageItem.objects.filter(client=client_id, itemstatushistory__isnull=False).distinct().count()
渲染时出现类型错误:“int”对象不可迭代
Hello I seem to be having some problem involving counting in Django. I have a list of items which only displays its latest status. All of these items that has a status "Destroyed" have been removed. This prints nicely.
status_items = models.StorageItem.objects.filter(client=client_id, itemstatushistory__isnull=False).distinct()
{% for item in status_items %}
{{item.itemstatushistory_set.latest|cut:"Destroyed"}}
{% endfor %}
But I can't count for some reason.
status_items = models.StorageItem.objects.filter(client=client_id, itemstatushistory__isnull=False).distinct().count()
TypeError while rendering: 'int' object is not iterable
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
status_items
之后将包含项目计数 --> 在
{% for item in status_items %}
模板中使用int 对象显然会产生错误。
您可以不使用
count()
并在模板中访问计数,如下所示:模板系统将为您调用
status_items.count()
。更多信息在这里: rendering-a-context编辑:
您可以像这样定义
status_items
:然后在模板中:
after
status_items
will contain the count of items --> anint
objectusing it in the template in
{% for item in status_items %}
will obviously generate an error.you can leave it without the
count()
and in the template access to the count like this:The template system will call
status_items.count()
for you. More infos here: rendering-a-contextEDIT:
you could define
status_items
like this:then in the template:
您已将
status_items
设置为整数,因此您无法对 status_items 中的项目执行操作。
你想达到什么目的?
You've set
status_items
to an integer, so you can't then dofor item in status_items
.What are you trying to achieve?
你使用的是哪个版本的 Django?
也许您可以考虑使用注释语法,如聚合和其他 QuerySet 子句中所述:
http://docs.djangoproject.com/en/dev/topics/db/aggregation/#aggregations-and-other-queryset-clauses
Which version of Django are you on?
Maybe you could consider using the annotate syntax like described here under Aggregations and other QuerySet clauses:
http://docs.djangoproject.com/en/dev/topics/db/aggregation/#aggregations-and-other-queryset-clauses