def count_customers_per_period(self):
if not self.request.GET.get('period'):
period = self.request.GET['period']
entry_date_production = datetime.datetime(2017, 6, 1)
start_date = CustomerProfile.objects.filter(user__date_joined__gte=entry_date_production).\
first().user.date_joined
end_date = CustomerProfile.objects.last().user.date_joined
def start_end_period(period):
start = start_date - datetime.timedelta(period)
end = start + datetime.timedelta(period)
if period == 'day':
while start < end:
array = np.array([])
count = CustomerProfile.objects.filter(user__date_joined__date=start_date).count()
array = np.append(array, count)
start_date += datetime.timedelta(1)
elif period == 'week':
start_end_period(7)
while start < week:
array = np.array([])
count = CustomerProfile.objects.filter(user__date_joined__range=[start, end])
array = np.append(array, count)
start = end + datetime.timedelta(1)
end = start + datetime.timedelta(7)
elif period == 'month':
start_end_period(months=1)
while start < end:
array = np.array([])
count = CustomerProfile.objects.filter(user__date_joined__range=[start, end])
array = np.append(array, count)
start = end + datetime.timedelta(1)
end = start + datetime.timedelta(months=1)
elif period == 'year':
start_end_period(years=1)
while start < end:
array = np.array([])
count = CustomerProfile.objects.filter(user__date_joined__range=[start, end])
array = np.append(array, count)
start = end + datetime.timedelta(1)
end = start + datetime.timedelta(years=1)
return array
在这种方法中,我定义了start_end_period()
函数,因为我需要你多次使用它。
问题:
每当我调用start
函数时end
和start_end_period()
都没有实例化,这是正常的吗?
以这种方式将函数放入方法中是一个好习惯吗?
答案 0 :(得分:2)
start
和end
是start_end_period
的本地版本,您不会返回它们,所以是的,它们在其他地方没有定义是正常的。如果需要,您需要分配返回的值:
def start_end_period(period):
start = start_date - datetime.timedelta(period)
end = start + datetime.timedelta(period)
return start, end
...
start, end = start_end_period(7)
我不会说这样的嵌套函数是一个好习惯。将此作为类中的单独方法更常见,并使用self.start_end_period(whatever)
显式调用它。