Django观点:优化代码

时间:2013-05-15 18:23:40

标签: django django-views

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

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

由于

1 个答案:

答案 0 :(得分: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))
相关问题