使用django-filter按名字或姓氏过滤

时间:2017-09-02 00:35:45

标签: python django-filter

我需要按名字或姓氏搜索用户表格过滤。

鉴于用户John Doe Smith,John是名字,Doe Smith是姓氏。

当我搜索John Smith时,它应该找到上面的用户。

我知道这只是实现this SO answer解决方案的问题,但我如何在django-filter中执行此操作并保留其他过滤字段,如emailphone

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)

1 个答案:

答案 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']