【问题标题】:How can I sort data by created month如何按创建月份对数据进行排序
【发布时间】:2020-10-04 11:37:10
【问题描述】:

我正在尝试按创建月份对数据库中的数据进行排序。并在我的模板中显示仅在特定月份创建的数据。但是错误说'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 %}

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

【问题讨论】:

    标签: python-3.x django django-models django-views django-templates


    【解决方案1】:

    sorted_by_month() 中,您正在创建一个Report() 实例,并将months_query 分配给该实例的month 字段。然后在您的上下文中设置它,然后您尝试在模板中进行迭代。

    因此,您正在尝试迭代 Report 实例的月份字段,这是不可迭代的。

    应该很容易解决。 month_query 应该设置为:

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

    【讨论】:

    • 谢谢。现在,如何获取 5 月份创建的所有帖子?
    • filter by monthReport.objects.filter(month__month=5)
    猜你喜欢
    • 2021-12-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-06
    • 1970-01-01
    • 2018-06-11
    相关资源
    最近更新 更多