Reputation: 99
Is it possible to define multiple querysets within the view function?
Upvotes: 2
Views: 3114
Reputation: 21
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 %}
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
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