-1

我的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()

我能做些什么来改善它吗?

谢谢

4

1 回答 1

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))
于 2013-05-15T21:21:57.987 回答