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