Django按月份和年份查询

时间:2020-03-04 09:52:44

标签: python django-queryset

我是django-python的新手,所以我需要其他详细信息。我所需要的只是以pdf形式提供月度报告,也以pdf形式提供年度报告。

来自我的model.py

class Case(models.Model):
case_number = models.CharField(max_length=50, blank=True, null=True, unique=True)
reference_choice = (
    ('Personal', 'Personal'),
    ('Court', 'Court'),
)
reference = models.CharField(max_length=20, choices=reference_choice, null=True)
date_of_filing = models.DateField('Date of Filing (mm/dd/yyyy)*', blank=True, null=True)
official_receipt = models.CharField(max_length=50, blank=True, null=True,)
complainant = models.CharField(max_length=150)
respondent = models.CharField(max_length=150)
case_title = models.CharField(max_length=200)

在我的views.py

class GeneratePDF(View):
model = Case
def get(self, request, *args, **kwargs):

    cases = Case.objects.filter.all()
    context = {
        'date': date,
        'cases': cases,

    }
    pdf = render_to_pdf('pdf/monthly_report.html', context)
    if pdf:
        response = HttpResponse(pdf, content_type='application/pdf')
        filename = 'monthly_report_%s.pdf' %('month')
        content = 'inline; filename="%s"' % (filename)
        response['Content-Disposition'] = content
        return response
    return HttpResponse('Not Found')

并在我的monthly_report.html上

<div class="container mt-4">
        <table class="table-" style="width:1200px">
          <thead class="thead-light">
            <tr>
                <th scope="col">Case Number</th>
                <th scope="col">Complainant</th>
                <th scope="col">Respondent</th>
                <th scope="col">Case Title</th>
                <th scope="col">Action Taken</th>
                <th scope="col">Remarks</th>
            </tr>
          </thead>
          <tbody>
                {% for case in cases %}
            <tr>
                <td>{{ case.case_number }}</td>
                <td>{{ case.complainant }}</td>
                <td>{{ case.respondent }}</td>
                <td>{{ case.case_title }}</td>
                <td>{{ case.mediated| yesno }}</td>
                <td>{{ case.remarks }}</td>
            </tr>
                {% endfor %}
          </tbody>
        </table>
    </div>

在我的代码上,我仅获取所有数据,但未过滤。

2 个答案:

答案 0 :(得分:1)

在行Case.objects.filter.all()

您可以过滤结果。但是看来您不是在这么做吗?

一个例子:

from django.utils import timzeone
Case.objects.filter(date__gte=timezone.now()-timezone.timedelta(days=1))

答案 1 :(得分:1)

因此您应该将查询更改为正确的过滤器。例如,您可以这样做

cases=Case.objects.all().filter(date_of_filing = sometime)