Django context Datetime 唯一日期
Django context Datetime unique date
我的模型中有一个像这样的 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 月
如何只显示一次日期?
你的查询似乎是这里的问题。
您可以在查询后立即应用 distinct。
这是它的样子
Blog.objects.order_by().distinct('timestamp__date').values('timestamp__date')
这会将日期时间字段转换为日期,然后您可以获得相同的值。
我的模型中有一个像这样的 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 月
如何只显示一次日期?
你的查询似乎是这里的问题。 您可以在查询后立即应用 distinct。 这是它的样子
Blog.objects.order_by().distinct('timestamp__date').values('timestamp__date')
这会将日期时间字段转换为日期,然后您可以获得相同的值。