Search code examples
djangodjango-templatesdjango-filterdjango-template-filtersdjango-context

Django context Datetime unique date


I have in my model one DateTimeField like this

timestamp = models.DateTimeField(auto_now=True)

I want to filter the displayed results in the template by date, but each date only once and the time not at all.

in my views,

def get_context_data(self, *args, **kwargs):
    context['date'] = Blog.objects.order_by().values('timestamp').distinct()
    return context

in my html template:

 <form id="filter-form" method="GET" action="">

    <select name="dt" id="date">
        <option value="">Filter by Date</option>
        <option value="">All</option>
        {% for filter in date %}
        <option value={{filter.timestamp|date:"m-d"}}>{{ filter.timestamp|date:"d. F" }}</option> <!-- date:"Y-m-d" -->
        {% endfor %}
    </select>
    <input type="submit" value="Filter"><p></p>
</form>

And later in the views I cach them like this:

def get_queryset(self, **kwargs):
    querydate= self.request.GET.get('dt')
    start_date = "2020-"+querydate+" 00:00:00"
    end_date = "2020-"+querydate+" 23:59:59"
    print(start_date)
    #return Blog.objects.filter(Q(timestamp__icontains=querydate))
    return Blog.objects.filter(Q(timestamp__lte='start_date',timestamp__gte='end_date'))

In my template, I have now displayed the same date several times.

    1. January
    1. January
    1. January

How can I display the date only once?


Solution

  • Your query seems to be the issue here. You can apply distinct right after query. Here how it would look

    Blog.objects.order_by().distinct('timestamp__date').values('timestamp__date')
    

    This will convert datetime feild to date and then you can get values out the same.