【问题标题】:Django tables 2 - how do i change the queryset of the model i am displaying?Django 表 2 - 如何更改我正在显示的模型的查询集?
【发布时间】:2021-06-11 22:06:35
【问题描述】:

我正在尝试在使用 django-tables2 的表中显示获取请求后的所有模型对象。它目前正在显示所有内容,我无法弄清楚如何在我看来基于模型 pk 过滤查询集:

views.py

class ViewJob(LoginRequiredMixin, SingleTableView):
    model = JobResults
    table_class = JobResultsTable

    template_name = 'app/viewjobresults.html'
    paginator_class = LazyPaginator
    table_pagination = {"per_page": 30}

    def get_context_data(self, **kwargs):
        """ ViewJob get_context_data request """
        context = super(ViewJob, self).get_context_data(**kwargs)

        print("ViewJob >get_context_data()")

        context['job_obj'] = Job.objects.get(pk=self.kwargs.get('pk'))

        # context['object_list'] = context['object_list'].filter(job_id=context['job_obj'].id)

        return context

模板 - app/viewjobresults.html

{% extends "base.html" %}
{% load render_table from django_tables2 %}

    {% render_table table %}

{% endblock %}

tables.py

class JobResultsTable(tables.Table):

    job = tables.Column(
        accessor='job_id.job_name',
        verbose_name='Job')

    results = tables.Column(
        accessor='results',
        verbose_name='Result')

    class Meta:
        attrs = {"class": "table is-bordered"}

当前呈现的表是查询集中的所有作业对象。我在视图 get_context_data() 中有特定的 job_obj 来过滤它,但是当我过滤 context['object_list'] (行散列)时,它仍然显示整个 JobResults 列表。如何更改给定表的查询集?

【问题讨论】:

    标签: python django django-tables2


    【解决方案1】:

    您可以使用get_table_data() 方法来修改您的查询集。

    class ViewJob(LoginRequiredMixin, SingleTableView):
    
        def get_table_data(self):
            job_pk = self.request.GET.get('pk')
            if job_pk:
                return Job.objects.get(pk=job_pk)
            else:
                return Job.objects.all()
    

    https://django-tables2.readthedocs.io/en/latest/pages/generic-mixins.html

    【讨论】:

      猜你喜欢
      • 2016-03-23
      • 1970-01-01
      • 2023-01-11
      • 2018-11-17
      • 1970-01-01
      • 1970-01-01
      • 2019-10-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多