0

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.

gamer
  • 603
  • 4
  • 20

1 Answers1

2

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

gogaz
  • 2,323
  • 2
  • 23
  • 31
  • can I get previous 1,2,3 and so on months start and end dates ? – gamer Sep 24 '19 at 08:29
  • 2
    You could also utilize [`__range`](https://docs.djangoproject.com/en/2.2/ref/models/querysets/#range) instead of `__gt` and `__lt`. – tfw Sep 24 '19 at 08:32
  • sure, just loop over a number of monthes and create new timestamps from that: `for i in range(1,4): datetime(now.year, now.month - i, 1)` – gogaz Sep 24 '19 at 08:33
  • prevdate= datetime.datetime(now.year, now.month, 2) - datetime.timedelta(seconds=1) . I did this to get 2nd previous month (july) but I am getting current date using this – gamer Sep 24 '19 at 08:39
  • 1
    [`datetime.datetime`](https://docs.python.org/3.7/library/datetime.html#datetime-objects): The constructor is `datetime(year, month, day, ...)`. What you're doing currently is getting the 2nd of the current month, e.g. 2019-09-02. – tfw Sep 24 '19 at 08:44
  • 2
    careful though, this algorithm does not work for January because the month `0` doesn't exist and will raise a `ValueError`, – gogaz Sep 24 '19 at 11:49
  • @gogaz I am having difficulites in getting month end . I am getting 8th month everytime . my code is now = timezone.now() one_month_ago = datetime.datetime(now.year, now.month - dynamicValue , 1) month_end = datetime.datetime(now.year, now.month, 1) - datetime.timedelta(seconds=1) – gamer Sep 24 '19 at 13:18
  • where dynamic value is 1 ,2 ,3 ,4 – gamer Sep 24 '19 at 13:19