import os

from django.conf import settings
from django.core.management.base import BaseCommand
import datetime
from registration.models import RegistrationProfile

from stats.models import ValueStore


class Command(BaseCommand):
    help = 'creates bulk shifts from existing data'
    args = ""

    option_list = BaseCommand.option_list

    def handle(self, *args, **options):
        shifts = RegistrationProfile.objects.all()\
            .filter(needs__time_period_from__date_time__lte=datetime.datetime.now())
        seconds = 0.0
        for shift in shifts:
            theshift = shift.needs.all()
            for single_shift in theshift:
                deelta = single_shift.time_period_to.date_time - single_shift.time_period_from.date_time
                seconds += deelta.total_seconds()
        total_hours = int(((seconds/60)/60))
        try:
            key = ValueStore.objects.get(name="total-volunteer-hours")
            key.value = total_hours
            key.save()
        except ValueStore.DoesNotExist:
            ValueStore.objects.create(name="total-volunteer-hours", value=total_hours)






@@ -1,47 +1,37 @@
-import os%0A%0Afrom django.conf import settings
+# coding: utf-8%0A%0Aimport datetime%0A
 %0Afro
@@ -79,31 +79,16 @@
 Command%0A
-import datetime
 %0Afrom re
@@ -132,17 +132,16 @@
 Profile%0A
-%0A
 from sta
@@ -484,16 +484,17 @@
 e.now())
+%5C
 %0A       
@@ -486,32 +486,201 @@
 now())%5C%0A        
+    .prefetch_related('needs', 'needs__time_period_to', 'needs__time_period_from')%5C%0A            .only('needs__time_period_to', 'needs__time_period_from')%0A%0A        total_
 seconds = 0.0%0A  
@@ -718,19 +718,25 @@
         
-the
+needs_in_
 shift = 
@@ -789,11 +789,17 @@
  in 
-the
+needs_in_
 shif
@@ -819,17 +819,16 @@
       de
-e
 lta = si
@@ -921,16 +921,22 @@
         
+total_
 seconds 
@@ -940,17 +940,16 @@
 ds += de
-e
 lta.tota
@@ -990,55 +990,58 @@
 int(
-((
+total_
 seconds
-/60)/60))%0A        try:%0A            key
+)/3600%0A%0A        value_object, created
  = V
@@ -1061,16 +1061,26 @@
 ects.get
+_or_create
 (name=%22t
@@ -1104,34 +1104,30 @@
 urs%22
-)%0A            key.
+, defaults=dict(
 value
- = 
+=
 tota
@@ -1133,29 +1133,27 @@
 al_hours
-%0A    
+))%0A
         
 key.save
@@ -1148,57 +1148,22 @@
     
-key.save()%0A        except ValueStore.DoesNotExist
+if not created
 :%0A  
@@ -1176,84 +1176,69 @@
     
-V
+v
 alue
-Store.objects.create(name=%22total-volunteer-hours%22, value=total_hours)%0A%0A%0A%0A%0A
+_object.value = total_hours%0A            value_object.save()
 %0A

Optimize worked hour calculation