简体   繁体   English

如何获取包含特定字符串的对象

[英]How to get objects that contain a specific string

I want to retrieve objects that contain a specific string in their CharField.我想检索在其 CharField 中包含特定字符串的对象。
In normal Python without Django, I can do this to check:在没有 Django 的正常 Python 中,我可以这样做来检查:

if "something" in string:
   pass

However, I don't know how to do so using .filter() in Django:但是,我不知道如何在 Django 中使用.filter()来做到这一点:

posts = Post.objects.filter(field = "string") # how can I do something like 'in' here?

I don't just want to get objects that have exactly the value as "string".我不只是想获得与“字符串”完全相同的值的对象。

Please teach me how to retrieve objects that contain a specific string in Django using .filter() .请教我如何使用.filter()在 Django 中检索包含特定字符串的对象。

You can use contains .您可以使用contains This will do case-sensitive containment test .这将进行区分大小写的遏制测试

Post.objects.filter(field__contains='string')

This will generate the following SQL query.这将生成以下 SQL 查询。

SELECT ... WHERE field LIKE '%string%'

See field lookups for more information.有关详细信息,请参阅字段查找

posts = Post.objects.filter(field__icontains = "string")

Chack here details在这里查看详细信息

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM