kengcc
kengcc

Reputation: 1881

Django rest framework - how to make case insensitive viewset search

How to enable case insensitive search in rest framework's viewsets?

For example, assuming Post model has a tag. All links below should find the same tag content, right now they are case sensitive and try to search for different values:

  1. /posts/tag=AbcDef
  2. /posts/tag=abcdef
  3. /posts/tag=AbcdeF

views.py

class PostViewSet(viewsets.ReadOnlyModelViewSet):
    queryset = Post.objects.all()
    serializer_class = PostSerializer

Upvotes: 4

Views: 6328

Answers (2)

Ben Hare
Ben Hare

Reputation: 4415

Did you look into using http://www.django-rest-framework.org/api-guide/filtering/#searchfilter ? That does case-insensitive searching by default.

Upvotes: 8

Anush Devendra
Anush Devendra

Reputation: 5475

Assuming that you have field called tag in Post model and your search url is of the form:

/posts/?tag=AbcDef

You can do case sensitive search like:

class PostViewSet(viewsets.ReadOnlyModelViewSet): 
    serializer_class = PostSerializer

    def get_queryset(self):
        keyword = self.request.query_params.get('tag', '')
        queryset = Post.objects.filter(tag__iexact=keyword)
        return queryset

Upvotes: 9

Related Questions