Query with min and max size in Django rest api

Viewed 1191

I have this model:

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)

The view is like this:

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

I am able to save the images with all these attributes. I want to have a query like this to return all the images with height greater than 100 and less than 300:

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

How to achieve this in Django?

I am getting 500 server error If I try to do fire the api with minheight empty GET /images/?minheight=

2 Answers

In general, the query would look like:

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

This uses the gt and lt field lookups. There are also variants for greater than or equal (gte) and less than or equal (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

You have to manually filter the queryset based on the GET parameters.

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

    def get_queryset(self):
        minheight = self.request.GET.get('minheight')
        maxheight = self.request.GET.get('maxheight')

        return self.queryset.filter(image_height__gte=minheight, image_height__lt=maxheight)
Related