28👍
You can use range lookup. Just find the lowest and greater date and then apply it as:
queryset.filter(created_at__range=(start_date, end_date))
12👍
You can use range e.g.
import datetime
first_date = datetime.date(2005, 1, 1)
last_date = datetime.date(2005, 3, 31)
queryset.filter(created_at__range=(first_date, last_date))
11👍
You can use __gte
(greater than or equal) and __lte
(less than or equal). For example:
queryset.filter(created_at__gte=datetime.date.today())
- Can you declare multiple with variables in a django template?
- Reset SQLite database in Django
- Django admin dropdown of 1000s of users
- Django template rows of multiple items
3👍
1👍
queryset.filter(created_at__range=(start_date, end_date)) this will lead to problem which is the end date will be exlusive let take example how will the sql will look to this query as created_at >= "start_date 00:00:00" AND created_at <= "end_date 00:00:00"
so the best solution is to add max time in date to the end date which is "23:59:59" so it will created_at >= "start_date 00:00:00" AND created_at <= "end_date 23:59:59"
so you can a achieve this by doing
import datetime
queryset.filter(created_at__range=(
datetime.datetime.combine(start_date, datetime.time.min),
datetime.datetime.combine(end_date, datetime.time.max),
))
also if adding 1 to end date this will be wrong approach because the end date will be end_date+1 00:00:00 so the query will include also the end_date+1 00:00:00 which is wrong
there is another answer for this we can change the datetimefield to datefield
queryset.annotate(Date = Cast('created_at', DateField())).filter(Date__range=(start_date,end_date))
and there is another answers you play around with it like
queryset.filter(Q(created_at__range=(start_date,end_date)) | Q(created_at__icontains=end_date) )
OR
queryset.filter(Q(created_at__range=(start_date,end_date)) | Q(created_at__startswith=end_date) )
- How to write unit tests for django-rest-framework api's?
- Git aws.push: No module named boto
- Improving Performance of Django ForeignKey Fields in Admin
- How do I get the django HttpRequest from a django rest framework Request?
- Django render_to_string() ignores {% csrf_token %}