我在Django的queryset遇到了一些麻烦。不幸的是,我不能使用构建在分页中的Django REST框架,因为它添加了未使用的JSON字段,如"next“、"previous”和"count",因此我希望限制在queryset上使用:10选项。
在下面的尝试中,我得到了错误:Queryset Cannot reorder a query once a slice has been taken.
class LocationsViewSet(viewsets.ReadOnlyModelViewSet):
serializer_class = serializers.LocationSerializer
ordering = ('location_name',)
def get_queryset(self):
queryset = models.GeonamesLocation.objects.all()
name_prefix = self.request.QUERY_PARAMS.get('name_prefix', None)
if name_prefix is not None:
if len(name_prefix) < 3:
raise exceptions.ParseError("'name_prefix' must consist of at least 2 characters")
queryset = queryset.filter(location_name__icontains = name_prefix).order_by('location_name', 'geonames_country', 'geonames_region')[:10]
return queryset
我理解如果我在执行[:10]
之前应用了order_by,为什么会得到这个错误,但是既然我是在之后执行这个错误,它为什么会给我这个错误?
谢谢,马克
发布于 2013-11-28 09:02:42
此错误发生在get_queryset返回queryset之后,因为LocationViewSet具有“oder”属性,该属性试图再次对查询集进行重新排序。
发布于 2013-11-28 08:52:33
您可以在代码中为10个结果编写原始查询,就像这样,
org = Organization.objects.raw('SELECT organization_id, name FROM organization where is_active=1 ORDER BY name limit 10')
在原始查询中保留一件事情,您必须始终获取表的主键,这是强制性的。这里,organization_id
是contact_organization
表的主键。
https://stackoverflow.com/questions/20270629
复制