代码之家  ›  专栏  ›  技术社区  ›  Pol Frances

django filter-我想用一个过滤器输入过滤不同的属性

  •  0
  • Pol Frances  · 技术社区  · 6 年前

    具有以下型号:

    class Project(models.Model):
        ...
        name = models.CharField(max_lenght=70)
        short_description = models.CharField(max_length=135)
        description = models.CharField(max_lenght=25000)
        ...
    

    我只想使用一个输入来查看 name , short_description description .

    例如,如果我有以下数据:

    对象1:

    name = "Amazing airplanes"
    short_description = "This project wants to be ..."
    description = "... ... ..."
    

    对象2:

    name = "Testing potatoes as batteries"
    short_description = "... ... ... "
    description = "... this project ..."
    

    小精灵:

    name = "project creator"
    short_description = "... ... ..."
    description = "... ... ..."
    

    我只过滤一个输入 project ,因此我必须得到这三个对象。(如果一个对象在几个属性中有相同的单词,那么它只需要返回一次该对象)

    我现在拥有的是:

    class ProjectListFilter(django_filters.FilterSet):
        name = django_filters.CharFilter(lookup_expr='icontains')
        short_description = django_filters.CharFilter(lookup_expr='icontains')
        description = django_filters.CharFilter(lookup_expr='icontains')
    
        class Meta:
            model = Project
            fields = ['name', 'short_description', 'description']
            queryset = Project.objects.all()
    

    但这会产生3个输入,这是我试图回避的。

    1 回复  |  直到 6 年前
        1
  •  0
  •   aliva    6 年前

    你应该为此编写一个自定义方法,检查 docs ,您的代码应该如下所示:

    class ProjectListFilter(django_filters.FilterSet):
        name = django_filters.CharFilter(method='my_filter')
    
        class Meta:
            model = Project
            fields = ['name', ]
    
        def my_filter(self, queryset, name, value):
             return queryset.filter(
                 name__icontains=value
             ) | queryset.filter(
                 short_description__icontains=value
             ) | queryset.filter(
                 description__icontains=value
             )