Whole-word match only in Django query

前端 未结 3 1962
-上瘾入骨i
-上瘾入骨i 2020-12-15 09:08

I am trying to write a Django query that will only match whole words. Based on the answer here, I\'ve tried something like:

result = Model.objects.filter(te         


        
3条回答
  •  温柔的废话
    2020-12-15 09:51

    You might be able to get something by dropping the regex and using a few django lookups

    result = Model.objects.filter(Q(text__contains=' someword ') |
                                  Q(text__contains=' someword.') |
                                  Q(text__istartswith = 'someword.' |
                                  Q(text__istartswith = 'someword.' |
                                  Q(text__iendswith = 'someword')
    

    see here for docs.

    I realize that's not so elegant (but makes for easy maintenance if you're not a fan of regex).

提交回复
热议问题