同比和环比

def get_electric_num_then(self, obj):
    data = self.context

    start_date = datetime.datetime.strptime(data['start_date'], '%Y-%m-%d')

    last_date = start_date - relativedelta(years=1)

    end_date = datetime.datetime.strptime(data['end_date'], '%Y-%m-%d')

    
     This_year = \
     ElectricNum.objects.values('num').filter(create_time__gte=start_date, create_time__lte=end_date).aggregate(
         Sum('num'))['num__sum']
    
    last_year = \
    ElectricNum.objects.values('num').filter(create_time__gte=last_date, create_time__lte=start_date).aggregate(
        Sum('num'))['num__sum']

   
     end_year_num = This_year if This_year else 0
 
     start_year_num = last_year if last_year else 0

     if end_year_num == 0:
         end_year_num=ElectricNum.objects.filter(create_time__lte=end_date).order_by('update_time')
         end_year_num=end_year_num.last().num

   
     return start_year_num,end_year_num

def get_electric_num_Chain(self,obj):
    data=self.context
    start_date = datetime.datetime.strptime(data['start_date'], '%Y-%m-%d')

    last_date_month = start_date - relativedelta(months=1)

    end_date = datetime.datetime.strptime(data['end_date'], '%Y-%m-%d')

    end_date_month= end_date - relativedelta(months=1)

    result_month = \
        ElectricNum.objects.values('num').filter(create_time__gte=end_date_month, create_time__lte=end_date).aggregate(
            Sum('num'))['num__sum']

    last_month = \
        ElectricNum.objects.values('num').filter(create_time__gte=last_date_month, create_time__lte=start_date).aggregate(
            Sum('num'))['num__sum']

    start_date_num=last_month if last_month else 0
    end_date_num=result_month if result_month else 0



    return start_date_num,end_date_num


class Meta:
    model = Device
    fields = ('electric_num_then','electric_num_Chain')

你可能感兴趣的:(同比和环比)