开发者

django DateTimeField list records by day

Hay, i have a field in one of my models which saves the creation date of 开发者_运维技巧an object

created_on = models.DateTimeField(blank=False, auto_now_add=True)

This works as expected.

In my templates i want to list objects like this

June 15
{{ objects here which was created on June 15 }}
June 14 
{{ objects here which was created on June 14 }}

etc

Any idea how i would go about doing this?

Thanks in advance.


First in the view, make sure your objects are ordered by the 'created_on' field.

object_list = MyObjs.objects.all().order_by('created_on')

I believe you should then be able to use the following code in your template:

{% regroup object_list by created_on|date:"Y-m-d" as objects_by_day %}

{% for day in objects_by_day %}
    {{day.list.0.created_on|date:"M d"}}
    {% for obj in day.list %}
        {{obj}}
    {% endfor %}
{% endfor %}

This makes use of the regroup template tag, grouping the items by day, creating a list of objects per day. The date itself is output by using the 'date' template filter to reformat the created_on field of the first item in that date's list.

[Note: I have not tested this!]


The place for this is in the template, not the view.

You want the ifchanged template filter, which you use like this:

<h1>Archive for {{ year }}</h1>

{% for entry in entries %}
    {% ifchanged %}<h3>{{ entry.date|date:"F" }}</h3>{% endifchanged %}
    <p>{{ entry.date|date:"j" }} - {{ entry.title }}</p>
{% endfor %}

In this example, every time the month changes, a heading showing the month will be printed.

ifchanged can do some relatively complex things (e.g. checking if multiple variables have all changed), and can have an optional else block - see the docs for more.


you can for example generate list of dates(by day on given interval) in your view ordered from min to max, and get all objects in this interval. Then create templatetag that takes 2 arguments queryset and date, and filter records which created(or something else) by your date.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜