简体   繁体   中英

How to get a 'month' field with query_set?

I have a model and it has a field 'month'. How do I get this field with query_set?

Model is returning a field called 'area' and I don't want to change it to month because I need field area for another function's query_set.

Field 'month' has name of month ex: 'January'.

my model

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 or 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)

You can use values which returns a QuerySet that returns dictionaries, rather than model instances, when used as an iterable.

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

You can write custom template tag. For example, if your custom tags/filters are in a file called month_name.py , your app layout might look like this:

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

And in your template you would use the following:

{% load month_name %}

Then write this for get 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]

Then in your template

{{ month|month_name }}

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