Is it possible to define multiple querysets within the view function?
-
1Possible duplicate of How to combine 2 or more querysets in a Django view?wim– wim2016-10-05 21:26:56 +00:00Commented Oct 5, 2016 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– Sardorbek Imomaliev2016-10-06 04:13:55 +00:00Commented Oct 6, 2016 at 4:13
-
@SardorbekImomaliev I'm using a Class based view.Tom Higgins– Tom Higgins2016-10-06 18:52:28 +00:00Commented Oct 6, 2016 at 18:52
-
@TomHiggins Did you solve you problem?Sardorbek Imomaliev– Sardorbek Imomaliev2016-10-10 09:20:16 +00:00Commented Oct 10, 2016 at 9:20
-
@SardorbekImomaliev I have! Thank you for all your help.Tom Higgins– Tom Higgins2016-10-13 12:52:44 +00:00Commented Oct 13, 2016 at 12:52
|
Show 2 more comments
2 Answers
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.
Comments
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 %}