When I create an item, I automatically add the creation date. The body written to the body itself, it is saved in the database and then displayed. And the creation time is automatically added to created_at . I need to display all the dates under which any items were created in sorted order.

- models.py

 from django.db import models class Todo(models.Model): body = models.TextField() created_at = models.DateTimeField(auto_now_add=True) 

--views.py

  def all(request): date = Todo.objects.order_by('created_at') return render(request, 'todo/all.html', {'date':date}) 

In the view, I try to use order_by and output it in the template

--all.html

  {% for date in date %} <h1>{{ date.created_at }}</h1> {% endfor %} 

Then I get this situation. This is practically what I need, but the output depends on the number of items under each date, and I just need to print the date once, that is, Oct. 13,2018 Oct. 13,2018 and Oct.14,2018 , each date once, how to achieve this result? enter image description here

  • Todo.objects.values_list('created_at', flat=True).order_by('created_at') - floydya
  • @floydya did not help, displays the same result as mine - karaname
  • Add more .distinct('created_at') to the end. - floydya

1 answer 1

 Todo.objects.values_list('created_at', flat=True).order_by('created_at').distinct('created_at') 

but keep in mind that distinct (* field_names) is only for PostgreSQL, in case you have another DBMS, you have an exception django.db.utils.NotSupportedError