Drennos
Drennos

Reputation: 313

Django: get_queryset after get_context_data

I am filtering my Project model objects by authenticated user using get_context_data in my ListView

class myprojects(LoginRequiredMixin, ListView):
    model = Project
    template_name = 'my_project_list.html'
    ordering = ['project_title']

    def get_context_data(self, *args, **kwargs):
        context = super(myprojects, self).get_context_data(**kwargs)
        context['my_projects'] = Project.objects.filter(engineer=self.request.user)
        return context

In template

{% for my_project in my_projects %}
{{ my_project }}
{% endfor %}

I have a form in my template to search for projects and I use a get_queryset on the same ListView. I receive the search but it does not filter in the template

class myprojects(LoginRequiredMixin, ListView):
    model = Project
    template_name = 'my_project_list.html'
    ordering = ['project_title']

    def get_context_data(self, *args, **kwargs):
        context = super(myprojects, self).get_context_data(**kwargs)
        context['my_projects'] = Project.objects.filter(engineer=self.request.user)
        return context

    def get_queryset(self, *args, **kwargs):
        context = super().get_queryset(*args, **kwargs)
        search = self.request.GET.get('buscar', None)
        print(search)
        if search:
            context = context.filter(
                Q(project_title__icontains=search) |
                Q(category__title__icontains=search)
            ).distinct()
        return context

Note: When I use {% for project in object_list %} instead of {% for project in my_projects %}, it searches without problems, but I no longer have the filter by user

Upvotes: 0

Views: 758

Answers (1)

iklinac
iklinac

Reputation: 15738

Just filter inside of get_queryset method

def get_queryset(self, *args, **kwargs):
    queryset = super().get_queryset(*args, **kwargs)
    search = self.request.GET.get('buscar', None)
    queryset = queryset.filter(engineer=self.request.user)
    if search:
        queryset = queryset.filter(
            Q(project_title__icontains=search) |
            Q(category__title__icontains=search)
        ).distinct()
    return queryset

Upvotes: 1

Related Questions