使用过滤器时如何使用django_tables2搜索

时间:2019-05-03 12:54:26

标签: filter filtering django-tables2

我的问题是过滤后我无法取回任何数据。 我的搜索字段是:id名称和姓氏。最后从客户端获取的两个是外键。

filters.py

private BackgroundWorker _bgw = new BackgroundWorker();
private Form2 _msg = new Form2();
private Form3 _msg2 = new Form3();

public Form1()
{
    _bgw.DoWork += BgwDoWork;
    _bgw.RunWorkerCompleted += BgwRunWorkerCompleted;
    _bgw.RunWorkerAsync();
    _msg.ShowDialog();
}

private void BgwDoWork(object sender, DoWorkEventArgs e)
{
    System.Threading.Thread.Sleep(5000);
}

private void BgwRunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
    _msg.Close();
    _msg2.ShowDialog();
}

models.py

class OrderFilter(django_filters.FilterSet):
    client__name = django_filters.CharFilter(lookup_expr='icontains')
    client__surname = django_filters.CharFilter(lookup_expr='icontains')

    class Meta:
        model = Order
        fields = ['id']

tables.py

class Order(models.Model):
    client = models.ForeignKey(Client,verbose_name=u'Client')

views.py

class OrderTable(tables.Table):

    #CUSTOM COLUMN EXAMPLE
    order_id=tables.Column(verbose_name= 'ID Order',orderable=False,empty_values=())

class Meta:
        #define the model
        model = Order
        exclude=('id')
        template_name = 'django_tables2/bootstrap.html'
        sequence = ("order_id")

我注意到,当我创建一个自定义查询集来填充表格时,例如:object_list = Order.objects.filter(order_created__gte = last_four_months).order_by('-invoice_date')过滤不起作用。

当我什么都没放时,它可以正常工作。

知道为什么会这样吗?

1 个答案:

答案 0 :(得分:0)

问题在于,我尚未定义我的自定义查询集必须插入到自定义表(tables.py)中,并且更重要的是要通过自定义过滤器(filters.py)进行过滤。

这样做之后,自定义查询集将正确过滤。

class OrderAYSListView(LoginRequiredMixin,SingleTableMixin,FilterView):
    login_url = '/login/'
    table_class = OrderTable2
    model = Order
    template_name='orders/order_ays_list.html'
    filterset_class = OrderFilter

    def get_context_data(self, **kwargs):
        context = super(OrderAYSListView, self).get_context_data(**kwargs)
        ##filter the orders of the past 4 months.
        last_four_months=date.today() - timedelta(120)
        object_list=Order.objects.filter(order_created__gte=last_four_months,ays=1).order_by('-invoice_date')

        f = self.filterset_class(self.request.GET, queryset=object_list)
        context['filter'] = f
        table = self.table_class(f.qs)
        RequestConfig(self.request).configure(table)
        context['table'] = table
        #clear all fields
        has_filter = any(field in self.request.GET for field in set(self.filterset_class.get_fields()))
        context['has_filter'] = has_filter
        return context