SupplierPart - Improve API

- The default DRF behaviour throws errors if the supplied query params do not conform to the limit_choices_to field
- This is non optimum! Don't want to have to handle these cases
- Do the filtering ourselves!
This commit is contained in:
Oliver Walters 2020-08-26 22:44:22 +10:00
parent d44ad541eb
commit 6ab34c3d0e

View File

@ -104,12 +104,41 @@ class SupplierPartList(generics.ListCreateAPIView):
queryset = super().get_queryset()
return queryset
def filter_queryset(self, queryset):
"""
Custom filtering for the queryset.
"""
queryset = super().filter_queryset(queryset)
params = self.request.query_params
# Filter by manufacturer
manufacturer = params.get('manufacturer', None)
if manufacturer is not None:
queryset = queryset.filter(manufacturer=manufacturer)
# Filter by supplier
supplier = params.get('supplier', None)
if supplier is not None:
queryset = queryset.filter(supplier=supplier)
# Filter by EITHER manufacturer or supplier
company = self.request.query_params.get('company', None)
company = params.get('company', None)
if company is not None:
queryset = queryset.filter(Q(manufacturer=company) | Q(supplier=company))
# Filter by parent part?
part = params.get('part', None)
if part is not None:
queryset = queryset.filter(part=part)
return queryset
def get_serializer(self, *args, **kwargs):
@ -147,9 +176,6 @@ class SupplierPartList(generics.ListCreateAPIView):
]
filter_fields = [
'part',
'supplier',
'manufacturer',
]
search_fields = [