【问题标题】:Django context Datetime unique dateDjango 上下文 Datetime 唯一日期
【发布时间】:2020-05-05 10:13:56
【问题描述】:

我的模型中有一个像这样的 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】:

    您的查询似乎是这里的问题。 您可以在查询后立即应用 distinct。 这是它的样子

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

    这会将日期时间字段转换为日期,然后您可以获得相同的值。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-03-05
      • 2016-07-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-10
      • 2014-04-07
      相关资源
      最近更新 更多