英文:
Queryset for search by username and display_name In Django Rest Framework
问题
-
我试图通过他们的用户名和显示名称来搜索用户。
-
我已经使用了这个开始匹配的方法。
search_obj = User.objects.exclude(user_uuid=token_user_uuid).filter(Q(display_name__istartswith=search_name)
| Q(username__istartswith=search_name)
).order_by('-created_on')[:10]
我得到了与我想要的答案相同的答案,但问题是如果显示名称是William Welch
,而我搜索Welch
,它应该返回该用户,但它没有返回该用户。
情况。
用户名:123William
显示名称:William Welch
如果搜索名称为12,则匹配
如果搜索名称为23w,则不匹配
如果搜索名称为Wil,则匹配
如果搜索名称为Welc,则匹配
如果搜索名称为elch,则不匹配
英文:
I'm trying to search users by their usernames and display names.
- I have used that for the starting match.
search_obj = User.objects.exclude(user_uuid=token_user_uuid).filter(Q(display_name__istartswith=search_name)
| Q(username__istartswith=search_name)
).order_by('-created_on')[:10]
I get the answer same as I want but the problem is if the display name is William Welch
and I search for Welch
It should return that user also, but it does not return that user.
cases.
username: 123William
display name: William Welch
if search_name 12 then match
if search_name 23w then not match
if search_name Wil then match
if search_name Welc then match
if search_name elch then not match
答案1
得分: 1
你可以使用__icontains
<sup>[Django文档]</sup>进行子字符串搜索:
from django.db.models import Q
search_obj = (
User.objects.exclude(user_uuid=token_user_uuid)
.filter(
display_name<b>__icontains</b>=search_name,
username<b>__icontains</b>=search_name,
_connector=Q.OR,
)
.order_by('-created_on')[:10]
)
如果你想搜索以特定词开头的内容,可以使用**__iregex
**查找 <sup>[Django文档]</sup>来使用正则表达式:
import re
from django.db.models import Q
rgx = fr'\y{re.escape(search_name)}'
search_obj = (
User.objects.exclude(user_uuid=token_user_uuid)
.filter(
display_name<b>__iregex=rgx</b>,
username<b>__iregex=rgs</b>,
_connector=Q.OR,
)
.order_by('-created_on')[:10]
)
英文:
You can search with __icontains
<sup>[Django-doc]</sup> to look for a substring instead:
<pre><code>from django.db.models import Q
search_obj = (
User.objects.exclude(user_uuid=token_user_uuid)
.filter(
display_name<b>__icontains</b>=search_name,
username<b>__icontains</b>=search_name,
_connector=Q.OR,
)
.order_by('-created_on')[:10]
)</code></pre>
If you want to search for starting words, you can work with a regex with the __iregex
lookup <sup>[Django-doc]</sup>:
<pre><code>import re
from django.db.models import Q
rgx = fr'\y{re.escape(search_name)}'
search_obj = (
User.objects.exclude(user_uuid=token_user_uuid)
.filter(
display_name<b>__iregex=rgx</b>,
username<b>__iregex=rgs</b>,
_connector=Q.OR,
)
.order_by('-created_on')[:10]
)</code></pre>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论