Django context Datetime unique date

问题描述 投票:0回答:1

我的模型中有一个类似DateTimeField的

timestamp = models.DateTimeField(auto_now=True)

我想按日期过滤模板中显示的结果,但每个日期仅一次,而时间则完全没有。

在我看来,

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

在我的html模板中:

 <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>

然后在视图中,我像这样对它们进行缓冲:

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'))

在我的模板中,我已经多次显示相同的日期。

    1. 一月
    1. 一月
    1. 一月

如何只显示一次日期?

django django-templates django-filter django-template-filters django-context
1个回答
0
投票
您的查询似乎是这里的问题。您可以在查询后立即应用不同的权限。这里看起来如何

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

这将日期时间字段转换为日期,然后您可以从中获得相同的值。
© www.soinside.com 2019 - 2024. All rights reserved.