2013-05-15 65 views
-1

我的views.py有問題。我重複了很多代碼,我想知道是否可以優化。Django意見:優化代碼

這裏是我的代碼:

簡介:

def profile(request, id): 
    if 'person' in request.session: 

     me = Users.objects.get(pk=session) 

     total_songs = songs.count() 
     total_fans = fans.count() 
     total_friends = amigos.count() 

     total_storage = porcentajeAlmacenamiento(me); 
     storage_left = almacenamientoRestante(me); 
     notifications = Notification.objects.all().filter(receptor=session, leido=0) 
     total_notifications = notifications.count() 

     return render_to_response("profile.html", { 
      'total_amigos': total_amigos, 
      'total_fans': total_fans, 
      'total_songs': total_songs, 
      'me': me, 
      'total_storage': total_storage, 
      'storage_left': storage_left, 
      'notificaciones': notificaciones, 
      'total_notifications': total_notifications},context_instance=RequestContext(request)) 
    else: 
     return HttpResponseRedirect('/login/') 

首頁:

def home(request): 
    if 'person' in request.session: 

     me = Users.objects.get(pk=mi_session) 
     songs = Song.objects.filter(autor__in = Friend.objects.filter(usuario=yo).values_list('amigo', flat=True)).order_by('-fecha_subida') 
     comments = Comment.objects.all().filter(cancion__in=canciones) 

     total_songs = songs.count() 
     total_fans = fans.count() 
     total_friends = amigos.count() 

     total_storage = porcentajeAlmacenamiento(me); 
     storage_left = almacenamientoRestante(me); 
     notifications = Notification.objects.all().filter(receptor=session, leido=0) 
     total_notifications = notifications.count() 

     return render_to_response('index.html', { 
      'total_friends': total_friends, 
      'total_fans': total_fans, 
      'total_songs': total_songs, 
      'total_storage': total_storage, 
      'storage_left': storage_left, 
      'me': me, 
      'comments': comments, 
      'notifications': notifications, 
      'total_notifications': total_notifications, 
      'songs': songs}, context_instance = RequestContext(request)) 
    else: 
     return HttpResponseRedirect('/login/') 

正如你可以看到,有一個重複到幾乎所有視圖的代碼的一部分:

total_songs = songs.count() 
    total_fans = fans.count() 
    total_friends = amigos.count() 

    total_storage = porcentajeAlmacenamiento(me); 
    storage_left = almacenamientoRestante(me); 
    notifications = Notification.objects.all().filter(receptor=session, leido=0) 
    total_notifications = notifications.count() 

是有什麼我可以做的改善它?

謝謝

+4

只是將其解壓縮到一個方法,並返回一個字典 – karthikr

+0

我怎麼可以連接這個字典其他參數? –

+1

我們在這裏提到的其他參數是什麼? – karthikr

回答

1

顯而易見的方法是讓一個函數返回一個字典。 在你看來,你將創建與其餘鍵的字典,你只想做一些事情大致如下:

general_data = get_general_dict() # the redundant keys 
specific_data = {'comments':comments, etc.) 
specific_data.update(general_data) 
return render_to_response('index.html', specific_data, context_instance = RequestContext(request))