Skip to main content
 首页 » 编程设计

python之在 Django 中搜索名字和姓氏

2024年08月14日47daizhj

我在 Django 上有这个模型:

class Profile(models.Model): 
  name = models.CharField(max_length=50, blank = False) 
  surname = models.CharField(max_length=100, blank = False) 
  ... 

例如,我在数据库中有 2 个配置文件:

  • 李四
  • 约翰·史密斯

我想做一个表单搜索,搜索名字和姓氏属性。

我试过:

Q(name__icontains=text) | Q(surname__icontains=text) 

但这不起作用,例如,如果我搜索“John Doe”,它会同时返回它们。

编辑: 基本上我想要的是“加入”要搜索的姓名和姓氏属性,所以当我搜索“John”时,它会显示“John Doe”和“John Smith”,当我搜索“John Doe”时,它会显示我只有“John Doe”个人资料。

请您参考如下方法:

试试这个,

from django.db.models import Value as V 
from django.db.models.functions import Concat 
 
text = "John Doe" 
Profile.objects.annotate(full_name=Concat('name', V(' '), 'surname')).filter(full_name__icontains=text)

引用

  1. Concat DB fucntion
  2. Django queryset filter after a concatenation of two columns

Django shell 输出

In [14]: from django.db.models import Value as V                                                                                                                                                                    
 
In [15]: from django.db.models.functions import Concat                                                                                                                                                              
 
In [16]: text = "John Doe"                                                                                                                                                                                          
 
In [17]: Profile.objects.annotate(full_name=Concat('name', V(' '), 'surname')).filter(full_name__icontains=text)                                                                                                    
Out[17]: <QuerySet [<Profile: John Doe>]> 
 
In [18]: text = "john"                                                                                                                                                                                              
 
In [19]: Profile.objects.annotate(full_name=Concat('name', V(' '), 'surname')).filter(full_name__icontains=text)                                                                                                    
Out[19]: <QuerySet [<Profile: John Doe>, <Profile: John Smith>]> 
 
In [20]: text="smith"                                                                                                                                                                                               
 
In [21]: Profile.objects.annotate(full_name=Concat('name', V(' '), 'surname')).filter(full_name__icontains=text)                                                                                                    
Out[21]: <QuerySet [<Profile: John Smith>]>