python - 在 Django 中搜索姓名和姓氏
问题描述
我在 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)
参考
Django 外壳输出
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>]>
推荐阅读
- sql-server - 为什么我在添加可选默认值时收到错误消息:“不允许对 'SYSTEM' 或 'INTEGRATION' 用户进行修改。”?
- c# - 如何更改 groupBox.Text?
- python - 如果语句不响应带有 neopixel 的 int 输入
- python - 是否可以使用日期参数 pd.read_csv 数据?
- javascript - 将 flex 属性应用于 React 映射项
- quasar-framework - 进行选择时,如何自定义 Quasar 的 QSelect 以粗体显示文本和轮廓
- c - 如何将 MPI_Reduce 转换为 MPI_Send 和 MPI_Recv?
- r - 如何删除函数中的自动文本?
- python - (优化帮助)在python中寻找5个邮箱投3封信的方法
- python - 我已经开始学习烧瓶,当我运行 home.html 并提交表单时,它会导致您的文件无法访问。对于后端,我使用了烧瓶