简体   繁体   中英

Condtional query_set in Djano Pagination generic LISTCREATEAPIview

I have a URL having some query_params in it and I have applied pagination onto this URL.

urls.py

url(r'^users/(?P<pk>[0-9]+)/workouts/get/$',
        WorkoutList.as_view(serializer_class=WorkoutSerializer), name='list'),

views.py

class WorkoutList(generics.ListCreateAPIView):
    queryset = Workout.objects.all()
    serializer_class = WorkoutSerializer
    permission_classes = (UserPermissions,)

    def get_queryset(self):
        query_set = super(WorkoutList, self).get_queryset()
        query_params = self.request.QUERY_PARAMS.dict()
        try:
            date = string_to_date_convertor(query_params['date'])
        except KeyError:
            print 'Exception'
            return Response(status=status.HTTP_406_NOT_ACCEPTABLE)

        if 'date' in query_params:
            query_set = Workout.objects.filter(created__contains=date, user_id = self.kwargs['pk'])

        elif 'date' in query_params and 'exclude_app_install_time' in query_params:
            query_set = Workout.objects.filter(created__contains=date, time_reg = query_params['exclude_app_install_time'])    


        return query_set

Now I have try except block around date and if date param is not there do nothing and just return 4xx Http status code. Also if no params are there just return with 4xx status code.

In case both of the condition block fails it is returning the query_set and executing this query_set

queryset = Workout.objects.all() My Workout tables contain millions of entries and I don't want to return the whole table. That would be catastrophic.

SO I added another conditional block like this

 elif query_param is None:
       query_set = None

In simple words if any of the exception or conditional block fails then just return 4xx.

You can return an EmptyQuerySet using QuerySet.objects.None() when any of the exception or conditional block fails.

# return empty queryset
queryset = Workout.objects.none()

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