Django视图:优化代码



我的views.py有问题。我重复了很多代码,我想知道是否有可能优化。

下面是我的代码:

简介:

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()
我能做些什么来改善它吗?

谢谢

最明显的方法是让函数返回一个字典。在您的视图中,您将使用剩下的键创建一个字典,并且您将按照以下行执行操作:

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))

最新更新