我有一个模型,并且有一个字段“ month”。如何使用query_set获取此字段?
模型正在返回一个名为“ area”的字段,我不想将其更改为month,因为我需要另一个函数的query_set的字段区域。
字段“ 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)
我的views.py或我的函数:
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)
答案 0 :(得分:0)
您可以使用values
来返回一个QuerySet,该查询集在用作迭代时将返回字典,而不是模型实例。
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 }}