Hugo
Hugo

Reputation: 53

Query all objects by date | Django REST framework

I would like to add an URL like 'reports/'int:year'/month/'int:month'' and list all the reports that I have for that month of that year

Currently, my view.py is like that :


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

In Django I did it like this :

urls.py :

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

Views.py :

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

What are the steps to have something similar in DRF?

Thanks!

Upvotes: 0

Views: 947

Answers (1)

Hugo
Hugo

Reputation: 53

Following @shad0w_wa1k3r comment, what I did is , i Overided the current Viewset and following DRF 'filtering-against-query-parameters' example i ended up doing this :

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

It works, I'll tweak it a bit, but I guess on front-end, I'll just need to do an ajax request with the date parameter to get the desired reports.

Upvotes: 1

Related Questions