我的代码中有以下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 原则。
那么我怎样才能重新组织这段代码,使其更符合逻辑并且不损害DRY原则呢?