Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django Query same week last year

I need to compare sums of events in the same week (isocalendar), year over year.

class MyModel(models.Model):
    date = models.DateTime(...
    hits = models.IntegerField(...

I've got this sorted for last year, last month, same month last year, same day last year using variations on:

same_month_last_year = MyModel.objects.filter(date__month = (datetime.datetime.now().month), date__year = (datetime.datetime.now() - relativedelta(years = 1)).year).aggregate(total=Sum('hits')['total']

I don't see an equivalent 'week' function. I can use .isocalendar()[1] on the right side of the equation but that's of no help on the left. Any ideas? Thanks.

like image 740
William Avatar asked Apr 27 '26 14:04

William


1 Answers

Django 1.11 added a week filter. Can you use that?

If not, you might be able to look at the source code and cherry pick it.

As a last resort, you could use Python to calculate the date range for the same week last year, then pass those dates as filters to the Django query.

like image 51
Don Kirkby Avatar answered Apr 30 '26 04:04

Don Kirkby



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!