Django, how to use filter to check if string field is contained in parameter

后端 未结 2 1913
滥情空心
滥情空心 2020-12-21 07:54

Say, I have a model with a text field:

class SomeModel
    keyword=models.CharField(null=True, max_length=255)

Now, I know how to check if

2条回答
  •  臣服心动
    2020-12-21 08:36

    Here is a solution that will select SomeModel rows whose keyword is any substring of the querystring, not just complete words:

    SomeModel.objects\
        .annotate(querystring=Value(querystring, output_field=CharField()))\
        .filter(querystring__icontains=F('keyword'))
    

    See docs for info about annotate, Value expressions and F expressions

提交回复
热议问题