I am using axios to get some data from my backend API made with django. Something very very wired is happening and I have been debugging this for hours.
This is the axios function that gets the data:
function useGetProducts(category: string, subcategory: string, code:string){
const [products, setProducts] = useState<Product[]>([]);
useEffect(() => {
axios.get(getQueryUrl(category, subcategory, code))
.then(response => {
console.log(response)
setProducts(response.data);
})
.catch(error => {
console.error(error);
});
},[]);
return products;
}
And here is my ProductView in django
class ProductView(viewsets.ModelViewSet):
serializer_class = ProductSerializer
def get_queryset(self):
queryset = Product.objects.all()
cat = self.request.query_params.get('category', None)
subcat = self.request.query_params.get('subcategory', None)
code = self.request.query_params.get('code', None)
if cat and subcat and code:
# Sanitize the name parameter using Django's ORM
queryset = queryset.filter(code__exact=code)
elif cat and subcat:
queryset = queryset.filter(category__exact=cat, sub_category__exact=subcat)
elif cat:
queryset = queryset.filter(category__exact=cat)
print(queryset)
return queryset
Now the thing is when the queryset contains only one element the response.data is an empty array but when the queryset contains more than one element the response.data contains the right amount of elements.
The method getQueryUrl works correctly. I tried to limit the output of other querysets that supposed to contain more than 1 element to 1 and same thing, empty array on the frontend side.
ChatGPT solution did not help either. It suggested that Django REST Framework serializes single objects differently from lists of objects and said that overriding the list method would fix the problem...but nope it didn't.
I highly believe the problem is with the API, most likely with django-rest-framework (DRF) but I'm new to django and don't know what may be causing this. Would appreciate any help.
By the way I am using the default DRF configurations.