首页 > 解决方案 > 按日期查询所有对象 | Django REST 框架

问题描述

我想添加一个类似'reports/'int:year'/month/'int:month'' 的 URL 并列出我在当年那个月拥有的所有报告

目前,我的 view.py 是这样的:


class ReportViewSet(viewsets.ModelViewSet):
    queryset = Report.objects.all()
    serializer_class = ReportSerializer

class ReportGroupData(ListAPIView):
    queryset=Report.objects.annotate(month=TruncMonth('date')).values('month').annotate(count=Count('id')).values('month', 'count').order_by('-month')
    serializer_class = ReportGroupMonthSerializer

在 Django 中,我是这样做的:

urls.py:

path('reports/<int:year>/month/<int:month>', ReportMonthArchiveView.as_view(month_format='%m'),
         name='report_archive_month'),

视图.py:

class ReportMonthArchiveView(MonthArchiveView):
    template_name = 'dashboard/reports_month.html'
    queryset = Report.objects.all()
    date_field = "date"
    allow_future = True
    paginate_by = 7

在 DRF 中进行类似操作的步骤是什么?

谢谢!

标签: djangodjango-rest-frameworkdjango-views

解决方案


在@shad0w_wa1k3r 评论之后,我所做的是,我覆盖了当前的视图集并遵循 DRF 'filtering-against-query-parameters' 示例,我最终这样做了:

class ReportViewSet(viewsets.ModelViewSet):
    queryset = Report.objects.all()
    serializer_class = ReportSerializer

    def get_queryset(self):

        queryset = Report.objects.all()
        date = self.request.query_params.get('date', None)
        if date is not None:
            queryset = queryset.filter(date=date)
        return queryset

它可以工作,我会稍微调整一下,但我想在前端,我只需要使用 date 参数执行 ajax 请求即可获得所需的报告。


推荐阅读