2

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

7
  • 1
    Possible duplicate of How to combine 2 or more querysets in a Django view? Commented 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? Commented Oct 6, 2016 at 4:13
  • @SardorbekImomaliev I'm using a Class based view. Commented Oct 6, 2016 at 18:52
  • @TomHiggins Did you solve you problem? Commented Oct 10, 2016 at 9:20
  • @SardorbekImomaliev I have! Thank you for all your help. Commented Oct 13, 2016 at 12:52

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.