在Django Rest API中搜索ListAPIView

时间:2019-02-18 11:25:38

标签: django django-models django-rest-framework django-views

我想使用API​​视图过滤列表视图。但这不是根据查询进行过滤。我该如何搜索查询。 this.budgetService.getBudgetDays(this.startDate, this.finishDate).pipe( catchError(res => this.budgetTestService.getBudgetDates(this.startDate, this.finishDate)), ).subscribe(res => { // res = value of getBudgetDays if no error, or getBudgetDates if there is one }); 方法可以为ListAPIView

POST

4 个答案:

答案 0 :(得分:2)

尝试一下

class JobsListAPIView(generics.ListAPIView):
     serializer_class = JobListSerialzer
      # pagination_class = ListLimitOffsetPagination
     permission_classes = [UserIsAuthenticated]

     def get_queryset(self, *args, **kwargs):
            # print('self.request.auth', self.request.auth.application.user.userprofile.user_company.id)

            qs = Jobs.objects.all()
            # if using body data json
            query = self.data.get("query")
            # else
            query = self.request.query_params.get("query")

        if query is not None:
            qs = qs.filter(job_status=query, job_company = self.request.auth.application.company).exclude(job_is_deleted = True)

        return qs

希望有帮助

有关更多详细信息,请遵循此link

答案 1 :(得分:0)

首先

您正在两次过滤数据。这是不必要的,因为这浪费时间和内存。

class JobsListAPIView(generics.ListAPIView):
    serializer_class = JobListSerialzer
    # pagination_class = ListLimitOffsetPagination
    permission_classes = [UserIsAuthenticated]

    def get_queryset(self, *args, **kwargs):
        # print('self.request.auth', self.request.auth.application.user.userprofile.user_company.id)


        query = self.request.data.get("query")
        print('query: ', query)

        if query:
            qs = Jobs.objects.exclude(job_is_deleted = True).filter(job_status=query, job_company = self.request.auth.application.company)
       else:
            qs = Jobs.objects.exclude(job_is_deleted = True).filter(job_company = self.request.auth.application.company
       )

        return qs

答案 2 :(得分:0)

您可以使用以下通用代码属性: 这段代码http:/.../?search = job_company

class AllListDataAPIView(generics.ListAPIView):
queryset = User.objects.all()
serializer_class = ProfileSerilizer
filter_backends = (filters.SearchFilter,)
search_fields = ['job_company']

答案 3 :(得分:0)

也许我的解决方案适用于某些人。

这个从 GET 参数创建一个过滤器字典,并用它过滤查询集。您可以将多个参数作为相同的键名发送,它将使用值列表。

<块引用>

?pk=1&pk=2

如果存在则返回两个对象

def get_queryset(self):
    queryset = self.queryset
    # convert request get to dict first to preserve list of values
    # then iterate over items
    filters = {key + '__in': value for key, value in dict(self.request.GET).items()}

    if isinstance(queryset, QuerySet):
        # Ensure queryset is re-evaluated on each request.
        queryset = queryset.all().filter(**filters)
    return queryset

您可以修改代码以在值列表上运行,方法是用“,”分割值的第一个元素:

<块引用>

?pk=1,2