45
Inspired by this question try this for MySQL
from django.db.models import Count
Product.objects.extra(select={'day': 'date( date_created )'}).values('day') \
.annotate(available=Count('date_created'))
6
Similar approach from San4ez‘s answer, but returning dates as ‘YYYY-MM-DD’ instead of ‘datetime.datetime(YYYY, MM, DD)’:
Product.objects.extra(select={'day': "TO_CHAR(date_created, 'YYYY-MM-DD')"})
.values('day') \
.order_by('day') \
.annotate(available=Count('date_created'))
- [Django]-Django – after login, redirect user to his custom page –> mysite.com/username
- [Django]-Django multiple and dynamic databases
- [Django]-Trying to parse `request.body` from POST in Django
1
In Django 1.4, you could use .dates('date_created', 'day')
instead of .values()
.
Try this code snippet:
Product.objects.annotate(available=Count('available_quantity')) \
.dates('date_created', 'day')
This should return:
[
{'date_created': datetime.datetime(2012, 4, 14), 'available': 2}, ...
]
- [Django]-Django choices. How to set default option?
- [Django]-Serializing list to JSON
- [Django]-Django: How to filter Users that belong to a specific group
0
You can try
Product.objects.extra(select={'day': "TO_CHAR(date_created, 'YYYY-MM-DD')"})\
.values('day')\
.order_by('day')\
.annotate(bets=Count('date_created'))
- [Django]-Django rest framework lookup_field through OneToOneField
- [Django]-403 Forbidden error when making an ajax Post request in Django framework
- [Django]-Override save method of Django Admin
0
By following the answer of San4ez and the changes from Zanon
For me i had to make a workaround to work with Postgres or Sqlite, since the Count() function will consider the datetime field, doesn’t matter if you going to create a "day" input just with the date because the date_created is still holding the time information, so multiple records with time on it wont be merged and counted up, after trying many things deferents i reached that way of skipping the time
Django 2.2
from django.db.models import Count
# Change date() to to_char(created_at, 'YYYY-MM-DD') if using Postgres
Product.objects.extra(select={'day': 'date( date_created )'})\
.values('day') \
.order_by('date_created__date')\
.annotate(available=Count('date_created__date'))
- [Django]-Celery. Decrease number of processes
- [Django]-No handlers could be found for logger
- [Django]-How do you configure Django to send mail through Postfix?