Django多级过滤器集

时间:2019-02-22 11:04:02

标签: python django django-filter django-filters

是否可以动态使用django_filters库中的django FilterSet,以便第二个下拉列表依赖于第一个下拉列表,第三个下拉列表取决于第一个下拉列表,依此类推。 可以说我有以下models.py

class CSV4(models.Model):
    var1 = models.CharField(max_length=100)
    var2 = models.CharField(max_length=100)
    var3 = models.CharField(max_length=100)
    var4 = models.CharField(max_length=100)
    var5 = models.CharField(max_length=100)
    var6 = models.CharField(max_length=100)
    var7 = models.CharField(max_length=100)
    var8 = models.CharField(max_length=100)
    var9 = models.CharField(max_length=100)

class CSVFilter(django_filters.FilterSet):
    entries = CSV5.objects.values_list('val1', flat = True).distinct()
    val1_choice = [(e, e) for e in entries]
    #print("e" , val1_choice)
    val1 = django_filters.ChoiceFilter(choices = val1_choice)

    entries = CSV5.objects.values_list('val2', flat=True).distinct()
    val2_choice= [(e, e) for e in entries]
    val2= django_filters.ChoiceFilter(choices=val2_choice)

    entries = CSV5.objects.values_list('val3', flat=True).distinct()
    val3_choice= [(e, e) for e in entries]
    val3= django_filters.ChoiceFilter(choices=val3_choice)

    entries = CSV5.objects.values_list('val4', flat=True).distinct()
    val4_choice = [(e, e) for e in entries]
    val4 = django_filters.ChoiceFilter(choices=val4_choice)

我的views.py

def filter_port(request):
    instance = CSV5.objects.values()
    user_filter = CSVFilter(request.POST or None, queryset=instance)

模板:

{% if user.is_authenticated %}

<form method="POST" id = "form1">
    {% csrf_token %}
    {{ filter.form }}
    <button name="filter_port" type="submit">Search</button>
</form>


<ul>
  {% for excel5 in filter.qs %}
        <li>
     {{ excel5.val5 }} - {{ excel5.val6 }} - {{ excel5.val7 }}
     - {{ excel5.val8 }} - {{ excel5.val9 }}


        <a href = "{% url 'appp:edit_results' excel5.id %}">
            <button>Edit</button>
        </a>

        </li>
  {% endfor %}
</ul>

{% endif %}
    return render(request, 'appp/filter_port.html', {'filter': user_filter})

因此,基本上,我在下拉列表中选择val1,只获取与val1相关的数据库中存在的val2字段的值。

示例:

可以说我的数据库如下:

1,2,3,4
5,6,7,8
1,3,4,5
5,7,8,9

我在第一个下拉列表中选择1作为val1,现在代替2、6、3和7作为val2(第二个下拉列表),我只想显示值2和3,因为它们“属于”值1.我希望我很清楚。任何帮助,将不胜感激。

0 个答案:

没有答案