基于URL中的warg的Django过滤器查询集

时间:2019-02-22 08:47:25

标签: django-rest-framework django-urls django-polymorphic

我正在尝试根据url中的kwarg过滤查询集。 我的网址是这样的:

http://localhost:8000/notification/all/?type="workflow"

我想过滤网址中是否存在type参数

class NotificationList(generics.ListAPIView):
    model = Notification
    serializer_class = NotificationSerializer

    def get_queryset(self):
        queryset =  Notification.objects.filter(created_for=self.request.user)[:int(settings.NOTIFICATION_PAGE_SIZE)]
        type_param = self.request.query_params.get('type')
        last = self.request.query_params.get('last')
        print("TYPE PARAm", type_param)

        if str(type_param)=="workflow":
                print("TRUEEEEEEEEEEEEEeeeee")
                queryset = Notification.objects.filter(created_for=self.request.user).instance_of(WorkflowNotification)

        if last:
            last_notification_created_on = Notification.objects.get(id=last)
            queryset = queryset.filter(created_on__lt=last_notification_created_on)


        return queryset

此刻,即使我在url中输入的类型为“ workflow”,也不会输入if条件。这可能是什么问题?

1 个答案:

答案 0 :(得分:1)

请应用此 http://localhost:8000/notification/all/?type=workflow

从网址中删除“

如果类型不是工作流,只会引发错误

if type == 'workflow':
  print("TRUEEEEEEEEEEEEEeeeee")
  queryset = ....
else:
    from rest_framework.exceptions import NotFound
    raise NotFound(detail="no notifications", code=404)