Vaibhav Jain
Vaibhav Jain

Reputation: 5507

Django how to list model objects date wise

I have a model from which I need to list all the objects from a given time period. For example: 10-05-2014 to 10-12-2014 And then I need to display the objects date wise. Meaning first display objects created on the start_date(10-05-2014) up until end_date(10-12-2014)

For example: 
    10-05-2014:
         objects list for that day
    11-05-2014:
         objects list for that day
    and so on until end_date

Query:

MyModel.objects.unsettled.filter(
            created_on__range=[start_date, end_date]
        )

But my problem is how do I list the query set in increasing order by date wise in my template. So that all the objects created on same date will be shown under that date. In short I want to display the list in sections divided by date.

MyModel.objects.unsettled.filter(created_on__range=[start_date, end_date]).order_by("created_on"). But it will just sort the list. How do I group the results.??

Upvotes: 1

Views: 644

Answers (1)

catavaran
catavaran

Reputation: 45575

Use the {% ifchanged %} template tag:

{% for obj in obj_list %}

    {% ifchanged %}
        <h2>{{ obj.created_on|date }}</h2>
    {% endifchanged %}

    <div>{{ obj.name }}</div>

{% endfor %}

Another (slightly more complex) option is to use the {% regroup %} tag.

Upvotes: 1

Related Questions