I'm trying to display all model objects after a get request in a table using django-tables2. It's currently displaying all and I can't figure out how to filter the queryset based on a model pk in my view:
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
template - 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"}
Currently the table rendered is ALL Job objects in a queryset. I have the specific job_obj in my view get_context_data() to filter this, but when i filter context['object_list'] (line hashed out) it still displays the entire list of JobResults. How can I change the queryset given to the table?
You can use the get_table_data()
method to modify your queryset.
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