首页 > 解决方案 > 在 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”个人资料。

标签: pythondjango

解决方案


尝试这个,

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数据库功能
  2. 两列连接后的 Django 查询集过滤器

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>]>

推荐阅读