django 有一种方法可以检查模型字段是否包含子字符串?

3htmauhk  于 2023-08-08  发布在  Go
关注(0)|答案(4)|浏览(144)

我想知道我能不能做到这样的事情:

full_string = "12345"
substring = "123"
Model.objects.filter.contains(field = substring)

字符串
或多或少像这样。总之,我想搜索一个子字符串,而不是字符串本身。

9wbgstp7

9wbgstp71#

查看Django contains和icontains

yyyllmsg

yyyllmsg2#

你可以使用contain和icontain来区分大小写/不区分字符串。
区分大小写:

Model.objects.filter.contains(field__contains = substring)

字符串
不区分大小写:

Model.objects.filter.icontains(field__icontains = substring)


注意双下划线!

b4lqfgs4

b4lqfgs43#

您可以使用

model_name.field.objects.filter(field__contains=substring)
model_name.field.objects.filter(field__icontains=substring)

字符串

0ve6wy6x

0ve6wy6x4#

现在你可以使用$regex操作符来匹配子字符串和字段中的值。
对于一个模型,person(使用mongoose),将name作为字段,我们可以搜索

let your_regular_expression = new RegExp(substring);
    person.find({name: { $regex : your_regular_expression}});

字符串
类似的事情也可以用原生mongodb来做。mongodb文档的链接在下面,您可以访问那里了解更多https://www.mongodb.com/docs/manual/reference/operator/query/regex/

相关问题