如何使用查询集获取“月”字段?

2024-04-25 23:24:38 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个模型,它有一个字段“月”。如何使用查询集获取此字段

模型正在返回一个名为“area”的字段,我不想将其更改为month,因为我需要另一个函数的查询集的字段area

字段'month'具有月份的名称,例如'January'

我的模型

class Report(models.Model):
    author = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name='Created by: ')
    year = models.IntegerField('Year:', default=2019)
    month = models.PositiveSmallIntegerField('Month', null=True, choices=MONTHS.items())
    area = models.ForeignKey(Area, on_delete=models.CASCADE, null=True, blank=True)
    country = models.ForeignKey(Country, on_delete=models.CASCADE, null=True, blank=True)
    new_ministers = models.IntegerField(default=0)

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

my views.py或my function:



def report_list(request):
    areas = Report.objects.all()

    context = {
        'areas':areas

    }
    return render(request, 'users/report_list.html', context)


def report_month(request):
    month = Report.objects.all()

    context = {
        'month': month
    }

    return render(request, 'users/report_month.html', context)

Tags: 模型reporttrueonmodelsrequestdefcontext
1条回答
网友
1楼 · 发布于 2024-04-25 23:24:38

当用作iterable时,可以使用values返回查询集,该查询集返回字典,而不是模型实例

month = Report.objects.values('month')

您可以编写自定义模板标记。 例如,如果自定义标记/过滤器位于名为month_name.py的文件中,则应用程序布局可能如下所示:

polls/
    __init__.py
    models.py
    templatetags/
        __init__.py
        month_name.py
    views.py

在模板中,您将使用以下内容:

{% load month_name %}

然后写下这个月的名字

import calendar
from django import template

register = template.Library()

@register.filter("month_name")
def month_name(month_number):
    return calendar.month_name[month_number]

然后在模板中

{{ month|month_name }}

相关问题 更多 >