gamer
gamer

Reputation: 613

Get data of table between 2 dates django python

I have a table in model like this

class ReviewMonthly(models.Model):
    user = models.ForeignKey(Profile, on_delete=models.CASCADE, related_name='ReviewMonthly')
    timestamp = models.DateTimeField(auto_now_add=True)
    value = models.FloatField()

i want to get data of value between two dates like I have saved data and the other is I am getting like datetime.datetime.now()

Update

when I tried to run following in my view.py

total_for_last_month =request.user.profile.ReviewMonthly (
        timestamp__gt=datetime.datetime.now() - relativedelta(months=1)
    ).aggregate(
        total=Sum('value')
    )['total']

I got this error

__call__() got an unexpected keyword argument 'timestamp__gt'

Upvotes: 1

Views: 488

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476503

You can filter with:

ReviewMonthly.objects.filter(timestamp__range=(first_datetime, timezone.now()))

Here first_datetime is a datetime object that contains the first timestamp.

If you want to use a check on the dates instead, you can use:

ReviewMonthly.objects.filter(
    timestamp__date__range=(first_datetime.date(), timezone.now().date())
)

As for the other queryset, you forgot to call .filter(...):

total_for_last_month =request.user.profile.ReviewMonthly.filter(
    timestamp__gt=datetime.datetime.now() - relativedelta(months=1)
).aggregate(
    total=Sum('value')
)['total']

Upvotes: 1

Related Questions