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?
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.
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.
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