如何按创建月份对数据进行排序

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

我试图在我的数据库中按创建月份对数据进行排序。并在我的模板中只显示某些月份创建的数据,但错误的是'datetime.date'不可迭代。但错误的说'datetime.date'是不可迭代的。有什么办法可以让我按月份对数据进行排序?

这是我的模型。

class Area(models.Model):
    name = models.CharField(max_length=30)

    class Meta:
        ordering = ["name"]

    def __str__(self):
        return self.name


class Report(models.Model):
    area = models.ForeignKey(Area, on_delete=models.CASCADE, null=True, blank=True)
    month = models.DateField(default=date.today)

    def __str__(self):
        return '{}'.format(self.area)

    def months(self):
        return self.month

这是我的views. py:

def report_list_by_month(request):    
    report = Report.objects.all().distinct('month')
    context = {

        'report': report
    }
    return render(request, 'report/report_list_by_month.html', context)

这是我的 report_list_by_month. html 和截图:

    {% for month in report %}
      <a href="{% url 'users:report-list-sorted-by-month' month.pk %}">{{month.month|date:"F"}}</a>
    {% endfor %}

Here is my report_list_by_month.html screen shot:

def sorted_by_month(request, pk):
    months = Report()
    months_query = months.month

    context = {
        'month': months_query    
    }
    return render(request, 'report/report_list.html', context)

这是我的report_list.html代码和错误截图:

{% for month in month %}
{{month}}
{% endfor %}

enter image description here

python-3.x django django-models django-views django-templates
1个回答
0
投票

sorted_by_month() 您正在创建 Report() 实例,并指定 months_querymonth 字段。 然后在你的上下文中设置这个字段,然后你尝试在模板中进行迭代。

因此,你试图在Report实例的月份字段上迭代,而这个字段是不可迭代的。

这应该很容易解决。 month_query 应该设置为类似于

months_query = Report.objects.all().distinct('month').order_by('month')
© www.soinside.com 2019 - 2024. All rights reserved.