I have a Django application where I have a view that returns the count of the users who did login today. Corresponding statement is as follows:
login_count= User.objects.filter(last_login__startswith=timezone.now().date()).count()
I want to get the count of users who did login once in the last week and last the month. Like, here timezone.now() returns today's date, is there anything like range which will cover a week or a month?
Yes, there is, and its even named range.
Example
import datetime
start_date = datetime.date(2005, 1, 1)
end_date = datetime.date(2005, 3, 31)
User.objects.filter(last_login__range=(start_date, end_date))
Of for the last week
today = datetime.date.today()
last_week = today - datetime.timedelta(days=7)
User.objects.filter(last_login__range=(last_week, today))
However,
Filtering a DateTimeField with dates won’t include items on the last day, because the bounds are interpreted as “0am on the given date”. If pub_date was a DateTimeField, the above expression would be turned into this SQL:
A quick solution would be to simply add a day, so the date range includes up to the last minute of today, but not more (also update last_week).
today = datetime.date.today() + datetime.timedelta(days=1)
last_week = datetime.date.today() - datetime.timedelta(days=7)
User.objects.filter(last_login__range=(last_week, today))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With