django - 按日期查询所有对象 | 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 中进行类似操作的步骤是什么?
谢谢!
解决方案
在@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 请求即可获得所需的报告。
推荐阅读
- python - 将 string.split() 作为参数传递给另一个函数时不起作用
- typescript - 在创建堆栈导航器之前如何导航到屏幕?
- sql - 使用计数选择最小值和最大值
- python - 在 Python 中实现表面模糊
- c - 有没有办法通过使用索引来迭代/递归二叉树?
- javascript - 如何在 Javascript HTML 文件中显示图像?
- java - 能够从 PDF 中删除页眉、页脚但同时删除页码 ex: 1/1 在此能够删除 1 但仍然 / 出现在文件的末尾
- python - 根据另一列更改列的值
- c# - asp.net framework 4.7配置日志级别,不工作
- python - 如何在 python 中将图像文件列表转换为单独的 pdf 文件?