[Django]-Django – multiple models(table) in one view

10πŸ‘

I might not understand your application, but if you want to load data from multiple models in a view, you can override the get_context_data method of the generic class based views. Here is an example using TemplateView.

from django.views.generic.base import TemplateView
from .models import Exam, Lawtext


class PageView(TemplateView):

    template_name = "pagename.html"

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['exams'] = Exam.objects.all()
        context['lawtexts'] = Lawtext.objects.all()
        return context

Then in your appname/templates/appname/pagename.html you have access to the data you queried in the view. In this case we get all the data from the models Exam and Lawtext. You could easily extend this.

{% for exam in exams %}
    <h4>{{exam.exammain}} </h4>
    <p>{{exam.rightanswer}}</p>
{% endfor %} 

{% for lawtext in lawtexts %}
    <p>{{lawtext.lawnamecode}}</p>
    <p>{{lawtext.lawcategory}}</p>
{% endfor %} 

OK, so I see you added added your views after I started writing my answer…
If you use function based views and return using render(), you can do this in a similar way. Your views.py can look something like this:

from .models import Exam, Lawtext

def exam_list(request):
    exams = Exam.objects.filter(writingdate__lte=timezone.now()).order_by('writingdate')
    lawtexts = Lawtext.objects.all()
    return render(request, 'boards/exam_list.html', {'exams': exams, 'lawtexts': lawtexts})
πŸ‘€filiphl

Leave a comment