我在index view
下面的代码在views.py
:组织代码视图
def index(request):
# Count all active polls for posting on the index page.
all_active_polls = Poll.objects.filter(pub_date__lte=timezone.now(),
is_active=True
).order_by('-pub_date')
num_of_active_polls = len(all_active_polls)
# Count all inactive polls for posting on the index page.
all_inactive_polls = Poll.objects.filter(pub_date__lte=timezone.now(),
is_active=False
).order_by('-pub_date')
num_of_inactive_polls = len(all_inactive_polls)
# Make the list of the last 5 published polls.
latest_poll_list = Poll.objects.annotate(num_choices=Count('choice')) \
.filter(pub_date__lte=timezone.now(),
is_active=True,
num_choices__gte=2) \
.order_by('-pub_date')[:5]
return render(request, 'polls/index.html', {
'latest_poll_list': latest_poll_list,
'num_of_active_polls': num_of_active_polls,
'num_of_inactive_polls': num_of_inactive_polls
})
在索引页我想有一个列表我的最后5个(或更多,并不重要)民意调查。 然后我想要两个链接:View all active polls(number of polls)
和View all closed polls(number of polls)
。所以我需要在index
视图代码中对它进行计数。 但是,我不确定这是放置此代码的最佳位置(即计数活动和非活动民意测验的数量)。
也可能我会在其他一些视图中需要这个数字,所以我会将这段代码复制到这个视图中?我认为它很痛DRY和Django重点坚持DRY原则。
那么,我该如何重组这个代码,使其更合乎逻辑,而不是伤害了原理?