Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can i query for objects in current year , current month in django

I need to find total objects created in

1. current year
2. current month
3. last month
4. last year

I am thinking like this

    this_year = datetime.now().year
    last_year = datetime.now().year -1
    this_month = datetime.now().month
    last month = (datetime.today() - timedelta(days=30)).month

Use like

Order.objects.filter(created_at__month=this_month)

The problem is

  1. last_month i want is calendar month not 30 days back
  2. i am not sure whether created_at__month=this_month will match current month or same month in previous year
  3. is it possible to get all counts in single query
like image 349
user3214546 Avatar asked Jan 23 '15 01:01

user3214546


People also ask

How do I get current year in Django?

The full tag to print just the current year is {% now "Y" %} . Note that the Y must be in quotes.

What is f() in Django?

An F() object represents the value of a model field, transformed value of a model field, or annotated column. It makes it possible to refer to model field values and perform database operations using them without actually having to pull them out of the database into Python memory.

How do you filter current year in Python?

The strfttime() function in Python is another method for obtaining the current year. The function strftime() takes a string specifying the date format as the argument. It returns the given date as a string in the provided format. We will pass "% Y" to strftime() to get the year of the date object.


1 Answers

today = datetime.datetime.now()

1 Current year

Order.objects.filter(created_at__year=today.year)

2 Current month

Order.objects.filter(created_at__year=today.year, created_at__month=today.month)

3 Last month

last_month = today.month - 1 if today.month>1 else 12
last_month_year = today.year if today.month > last_month else today.year - 1

Order.objects.filter(created_at__year=last_month_year, created_at__month=last_month)

4 Last year

last_year = today.year - 1
Order.objects.filter(created_at__year=last_year)

5 Single Query

As last year + current year includes last month and current month, and all orders>= last_year includes current year, the query is super simple:

Order.objects.filter(created_at__year__gte=last_year)
like image 95
Juan Fco. Roco Avatar answered Sep 28 '22 01:09

Juan Fco. Roco