django filter icontains match whole words only

前端 未结 3 1099
不知归路
不知归路 2021-01-02 10:22

I am using the filter icontains to search for words but I only want it to match whole words. e.g. if I searched for liver I wouldn\'t want it returning delivery.

my

相关标签:
3条回答
  • 2021-01-02 10:31

    It sounds like you want a Case-insensitive exact match.

    MyModel.objects.filter(title__iexact=search_word)
    

    http://docs.djangoproject.com/en/dev/ref/models/querysets/#lookup-iexact

    0 讨论(0)
  • 2021-01-02 10:45

    Regexp are usually enough : http://docs.djangoproject.com/en/dev/ref/models/querysets/#regex

    Please note that the regular expression syntax is that of the database backend in use.

    In python (sqlite) the regexp would be :

    \b(word)\b
    

    In Mysql you have :

    mysql> SELECT 'a word a' REGEXP '[[:<:]]word[[:>:]]';   -> 1
    mysql> SELECT 'a xword a' REGEXP '[[:<:]]word[[:>:]]';  -> 0
    
    0 讨论(0)
  • 2021-01-02 10:47

    In case you have angularjs and REST service implemented with tastypie or DRF, you can filter by whole words as $http.get(uri, {'params': {'display_name__iregex': '[[:<:]]word[[:>:]]'})

    of course, display_name should be enabled to filtering in Tastypie resource's Meta class as filtering = {'display_name': ALL,}

    0 讨论(0)
提交回复
热议问题