在 python django 中获取前几个月的数据
Get data of previous months data in python django
您好,我正在使用 django,我的模型如下所示
class SignupMonthlyPoint(models.Model):
user = models.ForeignKey(Profile, on_delete=models.CASCADE, related_name='SignupMonthlyPoints')
timestamp = models.DateTimeField(auto_now_add=True)
value = models.FloatField()
我得到了这样的最近 30 天的数据
def get_signupfromlinkmonthlypoints():
total_for_last_month =request.user.profile.SignupMonthlyPoint.filter(
timestamp__gt=datetime.datetime.now() - relativedelta(months=1)
).aggregate(
total=Sum('value')
)['total']
print(total_for_last_month)
但是当我分析它最近 30 天的数据时,不是上个月的数据。我想让它像 整个 8 月的数据,因为它是 9 月的最后一个月,然后是整个 7 月的数据,依此类推。
我先计算月份的开始日期和结束日期:
now = timezone.now()
one_month_ago = datetime.datetime(now.year, now.month - 1, 1)
month_end = datetime.datetime(now.year, now.month, 1) - datetime.timedelta(seconds=1)
然后得到对应的SignupMonthlyPoint
s:
SignupMonthlyPoint.objects.filter(user=request.user,
timestamp__gt=one_month_ago,
timestamp__lt=month_end)
您可能必须在日期上使用 timezone.make_aware()
来添加时区并让 Django 可以识别它们
您好,我正在使用 django,我的模型如下所示
class SignupMonthlyPoint(models.Model):
user = models.ForeignKey(Profile, on_delete=models.CASCADE, related_name='SignupMonthlyPoints')
timestamp = models.DateTimeField(auto_now_add=True)
value = models.FloatField()
我得到了这样的最近 30 天的数据
def get_signupfromlinkmonthlypoints():
total_for_last_month =request.user.profile.SignupMonthlyPoint.filter(
timestamp__gt=datetime.datetime.now() - relativedelta(months=1)
).aggregate(
total=Sum('value')
)['total']
print(total_for_last_month)
但是当我分析它最近 30 天的数据时,不是上个月的数据。我想让它像 整个 8 月的数据,因为它是 9 月的最后一个月,然后是整个 7 月的数据,依此类推。
我先计算月份的开始日期和结束日期:
now = timezone.now()
one_month_ago = datetime.datetime(now.year, now.month - 1, 1)
month_end = datetime.datetime(now.year, now.month, 1) - datetime.timedelta(seconds=1)
然后得到对应的SignupMonthlyPoint
s:
SignupMonthlyPoint.objects.filter(user=request.user,
timestamp__gt=one_month_ago,
timestamp__lt=month_end)
您可能必须在日期上使用 timezone.make_aware()
来添加时区并让 Django 可以识别它们