Ad

Get Data Of Previous Months Data In Python Django

Hi I am using django and my model look like this

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()

And I am getting last 30 days data like this

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)

but When I analyzed its last 30 days data not last month data. I want to make this like data of whole august month as it's last month of September, then data of whole july month and so on.

Ad

Answer

I'd start by calculating the month start and end dates :

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)

Then get the corresponding SignupMonthlyPoints:

SignupMonthlyPoint.objects.filter(user=request.user,
                                  timestamp__gt=one_month_ago,
                                  timestamp__lt=month_end)

You might have to use timezone.make_aware() on your dates to add timezone and make them recognizable by Django

Ad
source: stackoverflow.com
Ad