2

Is it possible to define multiple querysets within the view function?

Tom Higgins
  • 99
  • 2
  • 10

2 Answers2

3

Here is example

class MyMultiQuerysetView(TemplateView):
    def get_context_data(self, **kwargs):
        context_data = super().get_context_data(**kwargs)
        context_data['queryset1'] = MyModel1.objects.all()
        context_data['queryset2'] = MyModel2.objects.all()
        return context_data

And now queryset1 and queryset1 are acceptable in your templates.

Sardorbek Imomaliev
  • 14,861
  • 2
  • 51
  • 63
1

For class based views

class MyView(ListView):
    context_object_name = "data"
    template_name = "myapp/template.html"

    def get_queryset(self):
        myset = {
            "first": Model1.objects.all(),
            "second": Model2.objects.all(),
            .
            .
            .
        }
        return myset

In HTML you can call them like:

{% for a in data.first %}
{% for a in data.second %}

For function based views

def MyView(request):
    myset = {
        "first": Model1.objects.all(),
        "second": Model2.objects.all(),
        .
        .
        .
    }
    return render(request, "myapp/template.html", myset)

In HTML:

{% for a in first %}
{% for a in second %}
Berk Karaal
  • 11
  • 1
  • 4