我有一个普通的Django视图,该视图返回查询集的API。它从URL获取查询参数,并根据参数过滤数据库。它还输出最大长度为3个“零件”对象。
我想添加一些东西,以便它返回有关查询集是否被最大长度3限制的信息。这个想法是,由于输入的查询参数太模糊,因此将有太多数据从数据库中查询。因此,它已被裁剪,但是用户需要知道它已被裁剪。
当前代码如下所示
class PartList(generics.ListAPIView):
serializer_class = PartSerializer
def get_queryset(self):
"""
Optionally restricts the returned purchases to a given user,
by filtering against a `username` query parameter in the URL.
"""
queryset = Part.objects.all()
querydict = self.request.query_params
for (k, value) in querydict.items():
search_type = 'contains'
filter = k + '__' + search_type
queryset = queryset.filter(**{filter: value})
query_max_limit = 3
return queryset[:min(len(queryset), query_max_limit)]
最佳答案
您可以尝试获取四个元素,如果返回四个元素,则显示前三个元素,并指定数据被裁剪,例如:
def get_queryset(self):
"""
Optionally restricts the returned purchases to a given user,
by filtering against a `username` query parameter in the URL.
"""
queryset = Part.objects.all()
querydict = self.request.query_params
for (k, value) in querydict.items():
search_type = 'contains'
filter = k + '__' + search_type
queryset = queryset.filter(**{filter: value})
query_max_limit = 3
qs = queryset[:query_max_limit+1]
self.clipped = clipped = len(qs) > query_max_limit
if clipped:
return list(qs)[:query_max_limit]
else:
return qs
因此,此处
get_queryset
将返回一个集合(本身不是一个QuerySet
),该集合最多包含三个元素,并且它将设置一个属性self.clipped
,该属性指定是否对数据进行裁剪。或更优雅的方法是先计数,然后切片:
def get_queryset(self):
"""
Optionally restricts the returned purchases to a given user,
by filtering against a `username` query parameter in the URL.
"""
queryset = Part.objects.all()
querydict = self.request.query_params
for (k, value) in querydict.items():
search_type = 'contains'
filter = k + '__' + search_type
queryset = queryset.filter(**{filter: value})
query_max_limit = 3
qs = queryset[:query_max_limit+1]
self.clipped = clipped = qs.count() > query_max_limit
if clipped:
return queryset[:query_max_limit]
else:
return qs
最好将这种“剪切”逻辑移至专用函数,如果已剪切,则返回而不是设置属性。
关于python - 带有附加信息的Django View Return Queryset,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/52740321/