Django 更好的过滤日期的方法,无需在视图中进行硬编码
在 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以使用列表理解:
You could use a list comprehension: