在Django Rest API中使用最小和最大大小进行查询

时间:2018-12-24 14:20:01

标签: python django django-models django-rest-framework django-queryset

我有这个模型:

class Image(models.Model):
    image_name=models.CharField(max_length=30)
    image=models.ImageField(upload_to='images',width_field='image_width', height_field='image_height',)
    image_width=models.PositiveIntegerField(null=True, blank=True, editable=False)
    image_height=models.PositiveIntegerField(null=True, blank=True, editable=False)
    image_size=models.IntegerField(null=True, blank=True,editable=False)

视图如下:

class ImageViewSet(viewsets.ModelViewSet):
        queryset = Image.objects.all()
        serializer_class = ImageSerializer
        filter_backends = (DjangoFilterBackend, OrderingFilter,)
        filter_fields = ('image_name',)
        ordering_fields = ('id','image_name,)

我能够保存具有所有这些属性的图像。我想要一个这样的查询,以返回所有高度大于100且小于300的图像:

GET /images/?minheight=100&maxheight=300

如何在Django中实现这一目标?

我收到500台服务器错误,如果我尝试用minheight空启动api GET /images/?minheight=

2 个答案:

答案 0 :(得分:2)

通常,查询如下:

qs = models.Image.objects.filter(image_height__gt=100, image_height__lt=300)

这使用gtlt字段查找。大于或等于(gte)和小于或等于(lte)的变体。

class ImageViewSet(viewsets.ModelViewSet):
    serializer_class = ImageSerializer
    filter_backends = (DjangoFilterBackend, OrderingFilter,)
    filter_fields = ('image_name',)
    ordering_fields = ('id','image_name',)

    def get_queryset(self):
        queryset = Image.objects.all()
        minheight = self.request.query_params.get('minheight', '')
        maxheight = self.request.query_params.get('maxheight', '')

        if(minheight and maxheight):
            queryset = queryset.filter(image_height__gt=minheight,
                                       image_height__lt=maxheight)
        return queryset

答案 1 :(得分:2)

您必须基于 char *buffer1 = malloc(1024); ssize_t length = read(tunFd, buffer1, 1024); 参数手动过滤查询集。

GET