简体   繁体   中英

How can I sort data by created month

I am trying to sort data in my database by created month. And show data in my template created only certain month. But the error says that 'datetime.date' is not iterable. Any idea how can I sort data by month?

Here is my model:

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

Here is my 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)

Here is my report_list_by_month.html and screenshot:

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

这是我的 report_list_by_month.html 屏幕截图:

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

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

Here is my report_list.html code and error screenshot:

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

在此处输入图像描述

In sorted_by_month() you are creating a Report() instance, and assigning months_query to the month field of that instance. This then gets set in your context, and you attempt to iterate in the template.

Therefore you are trying to iterate over the month field of a Report instance, which is not iterable.

It should be easy to solve. month_query should be set to something like:

months_query = Report.objects.all().distinct('month').order_by('month')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM