I am having trouble in django on how to retrieve data from last week (not 7 days ago). Using date.isocalendar()[1] would be great. However Some stackoverflow browsing lead me to no satisfactory results.
Whatsoever, I could do without portability and use mysql’s INTERVAL function. This is the query I want to make using django’s ORM.
SELECT id, user_id, CAST(timestamp AS Date), WEEK(timestamp,3), WEEK(CURDATE(), 3) FROM main_userstats WHERE week(timestamp, 3) = WEEK(DATE_SUB(CURDATE(), INTERVAL 1 WEEK ), 3)
how can I do this using the extra function in django (if it’s not possible to do in any other simpler way)?
I assume what you are looking for are all the entries that belong to the same calendar week of the previous week.
This should do the trick:
To get the objects:
Note that I added 7 days to get the monday of the this week instead of adding 6 days to get the sunday of last week and that I used created_at__lt=monday_of_this_week (instead of __lte=). I did that because if your pub_date was a DateTimeField, it wouldn’t include the sunday objects since the time is 00:00:00 when using now().date().
This could easily be adjusted to consider Sunday as the first day of the week instead, but isocalendar() considers it the last, so I went with that.
If using Django < 1.4 use the following:
instead of: