[Answered ]-Query two models in Django into one queryset

1👍

You need to do something a little bit different here:

class SearchListView(ListView):
    queryset = Person.objects.filter(name__icontains="a")

    def get_context_data(self, **kwargs):
        context = super(SearchListView, self).get_context_data(**kwargs)
        context['book_queryset'] = Book.objects.filter(title__icontains="a")
        return context

Then in your view you can do somenting like the following:

{% for object in object_list %}
    <p>{{object}}</p>
{% endfor %}
{% for object in book_queryset %}
    <p>{{object}}</p>
{% endfor %}

The reason why the way you are using is not working is because ListView inherit from MultipleObjectMixin the queryset property and that property is passed to object_list context variable in the template, that happens under the hood and if you want to pass more context variables to the template you need to follow the approach I shared.

Leave a comment