2013-09-28 104 views
0

我在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原則。

那麼,我該如何重組這個代碼,使其更合乎邏輯,而不是傷害了原理?

回答

2

使用managers使其更幹,始終遵循原則 - 胖模型,薄視圖。 這裏是這樣做的一種方法:

models.py

class ActiveManager(models.Manager): 
    def get_query_set(self, active=True): 
     return super(ActiveManager, self).\ 
      get_query_set().filter(pub_date__lte=timezone.now(), is_active=active)\ 
          .order_by('-pub_date') 

class InctiveManager(InctiveManager): 
    def get_query_set(self): 
     return super(InctiveManager, self).get_query_set(is_active=False) 

class LatestManager(InctiveManager): 
    def get_query_set(self): 
     return super(LatestManager, self).get_query_set(is_active=True)\ 
             .filter(num_choices__gte=2)\ 
             .annotate(num_choices=Count('choice')) 

class Poll(models.Model): 
    ... 

    objects = models.Manager() 
    active = ActiveManager() 
    inctive = InctiveManager() 
    latest = LatestManager() 

views.py

all_active_polls = Poll.active.all() 
num_of_active_polls = len(all_active_polls) 

all_inactive_polls = Poll.inactive.all() 
num_of_inactive_polls = len(all_inactive_polls) 

latest_poll_list = Poll.latest.all()[:5] 
1

我必須問,有沒有一個原因,你沒有使用class based views

你可以有一個ListViewn最後投票在那裏你可以在get_queryset方法 不同的queryset另一個ListView控件定義號碼,如果你願意的或不同的一個視圖可以使用相同的模板。 另一個列表查看所有封閉的民意調查。

如果您想要在所有視圖中使用很多自定義代碼,只需編寫一個混合,以便您的所有其他基於類的視圖都將繼承。