Tom Higgins
Tom Higgins

Reputation: 99

How can I include multiple querysets in a django view?

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

Upvotes: 2

Views: 3114

Answers (2)

Berk Karaal
Berk Karaal

Reputation: 21

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 %}

Upvotes: 2

Sardorbek Imomaliev
Sardorbek Imomaliev

Reputation: 15390

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.

Upvotes: 3

Related Questions