在Django筛选中,可以使用或不使用空格进行搜索。

huangapple go评论80阅读模式
英文:

Search with or without space in django filter

问题

我有一个按名称搜索的功能,如果搜索匹配名称,应该返回一个人的名称。我需要显示有或没有空格的结果。例如:'A B C'应该显示结果A B Chacko,AB Chacko,AB Chaks等。类似地,搜索词'ABC'也需要列出上述结果。

try:
    term = request.GET['term']
    if term:
        queryset_primary = PrimaryUserSerializer(UserTable.objects.filter(Q(name__icontains=term) | Q(occupation__icontains=term)).order_by('name'), many=True, context=context).data
    else:
        pass
except:
    pass

模型只有'name'字段,没有名字和姓氏。

英文:

I have a search by name function, which should return the name of one person if the search matches the name.I need to show results with or without space between them. Eg: ‘A B C’
should show results A B Chacko, AB Chacko, AB Chaks etc. similarly, the search
The term ‘ABC’ needs also list the above results.

try:
    term = request.GET['term']
    if term:
            queryset_primary = PrimaryUserSerializer(UserTable.objects.filter(Q(name__icontains =term)|Q(occupation__icontains=term)).order_by('name'), many=True, context=context).data
    else:
        pass
except:
    pass

The models only have the 'name ' field not have first name, last name

答案1

得分: 1

请尝试以下代码,但这对性能很不好。

try:
    term = request.GET['term']
    if term:
        queryset_primary = PrimaryUserSerializer(UserTable.objects.filter(Q(name__icontains=term) | Q(name__istartswith=term) | Q(name__iexact=term) | Q(name__iendswith=term) | Q(name__startswith=trm) | Q(occupation__icontains=term)).order_by('name'), many=True, context=context).data
    else:
        pass

except:
    pass
英文:

Try this code but this is very bad for performance.

    try:
        term = request.GET['term']
        if term:
                queryset_primary = PrimaryUserSerializer(UserTable.objects.filter(Q(name__icontains =term) | Q(name__istartswith=term) | Q(name__iexact=term) | Q(name__iendswith=term) | Q(name__startswith=trm)| Q(occupation__icontains=term)).order_by('name'), many=True, context=context).data
        else:
            pass

except:
    pass

huangapple
  • 本文由 发表于 2020年1月6日 16:29:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/59608855.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定