Django 更好的过滤日期的方法,无需在视图中进行硬编码

发布于 2024-10-12 14:30:04 字数 947 浏览 2 评论 0原文

在 django 视图中,我过滤掉每年的内容,通过模板将其显示在图表中。目前我正在计算每年的手册,但必须有更好的方法来纠正代码,以便它只按年份过滤内容,而不必对年份进行硬编码。另外,在图表模板中,我还对年份进行了硬编码,并且想知道是否可以在不进行硬编码的情况下编写。

content_count_2006 = ContentItem.objects.filter(timestamp__year=2006).count()
content_count_2007 = ContentItem.objects.filter(timestamp__year=2007).count()
content_count_2008 = ContentItem.objects.filter(timestamp__year=2008).count()
content_count_2009 = ContentItem.objects.filter(timestamp__year=2009).count()
content_count_2010 = ContentItem.objects.filter(timestamp__year=2010).count()
content_count_2011 = ContentItem.objects.filter(timestamp__year=2011).count()

content_per_year = [content_count_2006, content_count_2007, content_count_2008, content_count_2009, content_count_2010, content_count_2011]


{% chart VerticalBarStack content_per_year %}
    {% axes type xy %}
    {% axes label "2006" "2007" "2008" "2009" "2010" "2011" %}
    {% color CCCCCC %}
{% endchart %}

In a django view I am filter out the content for each year to display it in a chart via a template. Currently I am doing the calculation for each year manual, but there has to be a better way to right the code so that it just filters the content by year without having to hardcode the years. Also in the chart template I am also hardcoding the year and was wondering that could be written without hardcoding.

content_count_2006 = ContentItem.objects.filter(timestamp__year=2006).count()
content_count_2007 = ContentItem.objects.filter(timestamp__year=2007).count()
content_count_2008 = ContentItem.objects.filter(timestamp__year=2008).count()
content_count_2009 = ContentItem.objects.filter(timestamp__year=2009).count()
content_count_2010 = ContentItem.objects.filter(timestamp__year=2010).count()
content_count_2011 = ContentItem.objects.filter(timestamp__year=2011).count()

content_per_year = [content_count_2006, content_count_2007, content_count_2008, content_count_2009, content_count_2010, content_count_2011]


{% chart VerticalBarStack content_per_year %}
    {% axes type xy %}
    {% axes label "2006" "2007" "2008" "2009" "2010" "2011" %}
    {% color CCCCCC %}
{% endchart %}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

巷雨优美回忆 2024-10-19 14:30:04

您可以使用列表理解:

content_per_year = [ ContentItem.objects.filter(timestamp__year=y).count() \ 
    for y in range(2006, 2012) ]

You could use a list comprehension:

content_per_year = [ ContentItem.objects.filter(timestamp__year=y).count() \ 
    for y in range(2006, 2012) ]
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文