When I set the fiterset_fields like below,
class SubCategoryViewSet(viewsets.ReadOnlyModelViewSet):
filter_backends = [DjangoFilterBackend]
filterset_fields = ["category_id"] # single underscore
I get this response when a category with the specified ID doesn't exist
{
"category_id": [
"Select a valid choice. That choice is not one of the available choices."
]
}
But when I set it like
class SubCategoryViewSet(viewsets.ReadOnlyModelViewSet):
filter_backends = [DjangoFilterBackend]
filterset_fields = ["category__id"] # notice the double underscore
I get a []
when a category with the specified ID doesn't exist.
Why does this happen? What is the right way to do this?
Why does this happen? What is the right way to do this?
This is partly one of the limitations of Django. If you use a fieldname, like category_id
, is one, it will first retrieve a collection if distinct values. If the entered value is not in it, then it can raise the exception.
If you work with JOINs, however, as is the case with category__id
, where you join on an extra model, that trick apparently is not implemented. It might be possible to do this, although it can be tricky for multiple JOINs, especially if there is some other filtering active that filters on another JOIN that partly overlaps. So since Django in that case can not derive a unique set of values, it fallsback on returning an empty list.
I would advise to use the first one, so category_id
. Indeed, if someone enters a wrong category_id
, it is more informative to say that the category_id
does not exist, and not return an empty list. In the latter case it gives the impression that the category exists, but that there is simply no subcategory with that category. Usually providing more information is better, of course if it is not "sensitive".