如何将 django_tables2 与过滤器一起使用?

How do I use django_tables2 with a filter?

我在网页上显示数据,我想迁移此代码以使用我在 tables.py 中创建的 table。我无法弄清楚如何在不破坏过滤器的情况下做到这一点。

views.py

def PlatListView(request):
    
    queryset = Plat.objects.all().values('id', 'description','status', 'phase__number','phase','schedule_found').annotate(lot_count=Sum('phase__lot_count')).order_by('description')

    f = PlatFilter(request.GET, queryset=queryset)
   
    return render(request, 'blog/filtertable2.html', {'filter': f})

filters.py

class PlatFilter(django_filters.FilterSet):
    community = ModelChoiceFilter(queryset=Community.objects.all())

tables.py

import django_tables2 as tables

class PlatTable(tables.Table):  

    id = tables.Column()
    description = tables.Column()
    status = tables.Column()
    phase__number = tables.Column()
    lot_count = tables.Column()
    schedule_found = tables.Column()
    
    class Meta:
        ordering = 'description'
        #model = Plat

filtertable2.html

{% extends "blog/base.html" %}
{% block content %}

{% load bootstrap4 %}

<form method="get">
        {{ filter.form.as_p }}
        <input type="submit" />
    </form>

 <table>
  <tr>
    <th>Description</th>
    <th>Status</th>
  </tr>
 {% for obj in filter.qs %}
  <tr>
    
        <td> {{ obj.description }}</td>
        <td>{{ obj.status }}</td>
   
  </tr>
   {% endfor %}
</table>
   
{% endblock content %}

我没有看到使用 Values QuerySet 的任何特殊原因,即 values()。您可以简单地使用 queryset:

注释该值
def plat_list_view(request):  # using snake_case when defining a method name.
    queryset = Plat.objects.annotate(lot_count=Sum('phase__lot_count')).order_by('description')
    f = PlatFilter(request.GET, queryset=queryset)
    return render(request, 'blog/filtertable2.html', {'filter': f})

在您看来,您使用过滤器中的数据构建了 table:

def PlatListView(request):
    queryset = Plat.objects.annotate(
        lot_count=Sum('phase__lot_count')
    ).order_by('description')

    f = PlatFilter(request.GET, queryset=queryset)
    table = <b>PlatTable(data=f.qs)</b>
    return render(request, 'blog/filtertable2.html', {'filter': f, <b>'table': table</b>})

然后您可以使用以下方式渲染 table:

{% extends "blog/base.html" %}
{% block content %}

{% load bootstrap4 %}
{% <b>load render_table from django_tables2</b> %}

<form method="get">
    {{ filter.form.as_p }}
    <input type="submit" />
</form>

{% <b>render_table table</b> %}
   
{% endblock content %}