Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django count objects created in current month

I have field in my model:

class Order(BaseModel):
    created_at = models.DateTimeField(auto_now_add=True)

I need to count all Order objects created in current month. How can I do this in my views?

like image 969
dease Avatar asked Nov 20 '13 13:11

dease


2 Answers

One of possible ways.

from datetime import datetime
current_month = datetime.now().month

Order.objects.filter(created_at__month=current_month)

See https://docs.djangoproject.com/en/stable/ref/models/querysets/#month for reference.

like image 200
Anatoly Scherbakov Avatar answered Nov 12 '22 16:11

Anatoly Scherbakov


The (current) accepted answer is incorrect. As stated in comments, maybe OP wants current month in current year. Not current month in any year. Well most people want the first.

So I would rather do

Order.objects.filter(created_at__gte=timezone.now().replace(day=1, hour=0, minute=0, second=0, microsecond=0))

The above also gets around timezone issues.

like image 13
victor n. Avatar answered Nov 12 '22 15:11

victor n.