Issue
class PublicUserViewSet(viewsets.ModelViewSet):
permission_classes = (IsAuthenticated,)
queryset = User.objects.all()
serializer_class = UserSerializer
filter_backends = [filters.SearchFilter,DjangoFilterBackend]
pagination_class = StandardResultsSetPagination
filterset_fields = {'id','username','deliveredtotime': ['gte', 'lte']}
When I give it a go with below parameter,it works:
filterset_fields = ['id','username','deliveredtotime']
It also works with
filterset_fields = {'deliveredtotime': ['gte', 'lte']}
But when I try to do as shown below:
filterset_fields = {'id','username','deliveredtotime': ['gte', 'lte']}
I get this:
Error:
filterset_fields = {'id','username','deliveredtotime': ['gte', 'lte']}
SyntaxError: invalid syntax ':'
How can I solve this problem?
Note: I know this is NOT a valid dictionary parameter. But I have looked at https://www.django-rest-framework.org/api-guide/filtering/ and didn't see any valid option. Does someone know how to work around it?
Solution
If you pass a list of fields, The Django filters turns it into a dictionary with the DEFAULT_LOOKUP_EXPR
as lookups.
So we can work with:
from django_filters.conf import settings
filterset_fields = {
'id': [settings.DEFAULT_LOOKUP_EXPR],
'username': [settings.DEFAULT_LOOKUP_EXPR],
'deliveredtotime': ['gte', 'lte'],
}
which is equivalent to:
from django_filters.conf import settings
filterset_fields = {
'id': ['exact'],
'username': ['exact'],
'deliveredtotime': ['gte', 'lte'],
}
but thus would allow Django filters to later change that.
It thus will filter on these fields only with the exact
filter.
Answered By - willeM_ Van Onsem
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.