我正在构建一个SaaS,它将使用Django Rest Framework通过NextJS(通用react框架)在前端管理多个网站。
我想根据发出请求的域过滤数据,在前端通过域发送的前端,在后端根据域过滤数据,问题是当我尝试使用下面得到的代码返回数据:
AttributeError: 'Response' object has no attribute 'model'
这是我的代码:
class ListProperties(generics.ListAPIView):
queryset = models.Property.objects.all()
serializer_class = frontend.PropertyCard
filter_class = filters.PropertyFilterset
pagination_class = pagination.PropertyPageNumberPagination
def get_queryset(self):
domain = self.request.META['HTTP_DOMAIN']
qs = self.filter_queryset(self.queryset.filter(company__domain=domain))
serialized = self.get_serializer(qs,many=True)
return Response(serialized.data)
预期结果应该是与通过标头传递的域相对应的数据。已过滤(如果应用了过滤器)并进行了分页。
答案 0 :(得分:2)
顾名思义,qet_queryset
[drf-doc]应该返回QuerySet
,而不是该查询集的响应。您应该只返回:
class ListProperties(generics.ListAPIView):
queryset = models.Property.objects.all()
serializer_class = frontend.PropertyCard
filter_class = filters.PropertyFilterset
pagination_class = pagination.PropertyPageNumberPagination
def get_queryset(self):
domain = self.request.META['HTTP_DOMAIN']
return self.queryset.filter(company__domain=domain)
list(..)
函数将automatically apply the defined filters [GitHub]:
def list(self, request, *args, **kwargs): queryset = self.filter_queryset(self.get_queryset()) page = self.paginate_queryset(queryset) if page is not None: serializer = self.get_serializer(page, many=True) return self.get_paginated_response(serializer.data) serializer = self.get_serializer(queryset, many=True) return Response(serializer.data)
(可选的)分页,序列化和响应的构造都由ListAPIView
[drf-doc]本身处理。如果要覆盖给定查询集的响应构造方式,则应覆盖list(..)
method [classy]。