Refactor buildlist filtering

This commit is contained in:
Oliver 2021-07-09 00:58:17 +10:00
parent bec98d355a
commit 7e7fe7d63f

View File

@ -5,11 +5,14 @@ JSON API for the Build app
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django_filters.rest_framework import DjangoFilterBackend
from django.conf.urls import url, include
from django.db.models import query
from rest_framework import filters
from rest_framework import generics
from django.conf.urls import url, include
from django_filters.rest_framework import DjangoFilterBackend
from django_filters import rest_framework as rest_filters
from InvenTree.api import AttachmentMixin
from InvenTree.helpers import str2bool, isNull
@ -19,6 +22,36 @@ from .models import Build, BuildItem, BuildOrderAttachment
from .serializers import BuildAttachmentSerializer, BuildSerializer, BuildItemSerializer
class BuildFilter(rest_filters.FilterSet):
"""
Custom filterset for BuildList API endpoint
"""
status = rest_filters.NumberFilter(label='Status')
active = rest_filters.BooleanFilter(label='Build is active', method='filter_active')
def filter_active(self, queryset, name, value):
if str2bool(value):
queryset = queryset.filter(status__in=BuildStatus.ACTIVE_CODES)
else:
queryset = queryset.exclude(status__in=BuildStatus.ACTIVE_CODES)
return queryset
overdue = rest_filters.BooleanFilter(label='Build is overdue', method='filter_overdue')
def filter_overdue(self, queryset, name, value):
if str2bool(value):
queryset = queryset.filter(Build.OVERDUE_FILTER)
else:
queryset = queryset.exclude(Build.OVERDUE_FILTER)
return queryset
class BuildList(generics.ListCreateAPIView):
""" API endpoint for accessing a list of Build objects.
@ -28,6 +61,7 @@ class BuildList(generics.ListCreateAPIView):
queryset = Build.objects.all()
serializer_class = BuildSerializer
filterset_class = BuildFilter
filter_backends = [
DjangoFilterBackend,
@ -97,34 +131,6 @@ class BuildList(generics.ListCreateAPIView):
except (ValueError, Build.DoesNotExist):
pass
# Filter by build status?
status = params.get('status', None)
if status is not None:
queryset = queryset.filter(status=status)
# Filter by "pending" status
active = params.get('active', None)
if active is not None:
active = str2bool(active)
if active:
queryset = queryset.filter(status__in=BuildStatus.ACTIVE_CODES)
else:
queryset = queryset.exclude(status__in=BuildStatus.ACTIVE_CODES)
# Filter by "overdue" status?
overdue = params.get('overdue', None)
if overdue is not None:
overdue = str2bool(overdue)
if overdue:
queryset = queryset.filter(Build.OVERDUE_FILTER)
else:
queryset = queryset.exclude(Build.OVERDUE_FILTER)
# Filter by associated part?
part = params.get('part', None)