我需要按名字或姓氏搜索用户表格过滤。
鉴于用户John Doe Smith,John是名字,Doe Smith是姓氏。
当我搜索John Smith时,它应该找到上面的用户。
我知道这只是实现this SO answer解决方案的问题,但我如何在django-filter
中执行此操作并保留其他过滤字段,如email
或phone
?
patient.py
(仅限相关部分)
class Patient(TimeStampedModel):
name = models.CharField('Name', max_length=30)
last_name = models.CharField('Last Name', max_length=30)
phone = models.CharField('Phone', max_length=14)
答案 0 :(得分:1)
我刚刚发现method
参数是我正在寻找的found here
基本上我的代码就这样结束了:
class PatientFilter(FilterSet):
name = CharFilter(name='name', lookup_expr='icontains')
last_name = CharFilter(name='last_name', lookup_expr='icontains')
phone = CharFilter(name='phone', lookup_expr='icontains')
full_name = CharFilter(name='full_name', method='search_by_full_name')
def search_by_full_name(self, qs, name, value):
for term in value.split():
qs = qs.filter(Q(name__icontains=term) | Q(last_name__icontains=term))
return qs
class Meta:
model = Patient
fields = ['name', 'last_name', 'phone']