Is it possible to define multiple querysets within the view function?
Asked
Active
Viewed 2,713 times
2
-
1Possible duplicate of [How to combine 2 or more querysets in a Django view?](http://stackoverflow.com/questions/431628/how-to-combine-2-or-more-querysets-in-a-django-view) – wim Oct 05 '16 at 21:26
-
Yes it is. Just add them to context. Which type of view are you using. Class based or function based? – Sardorbek Imomaliev Oct 06 '16 at 04:13
-
@SardorbekImomaliev I'm using a Class based view. – Tom Higgins Oct 06 '16 at 18:52
-
@TomHiggins Did you solve you problem? – Sardorbek Imomaliev Oct 10 '16 at 09:20
-
@SardorbekImomaliev I have! Thank you for all your help. – Tom Higgins Oct 13 '16 at 12:52
-
If my post helped. You can mark it as answer. So this question will shown as "answered" for other users. – Sardorbek Imomaliev Oct 13 '16 at 13:35
-
@SardorbekImomaliev Sorry, I've now done that. Thank you again! – Tom Higgins Oct 13 '16 at 13:40
2 Answers
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