从数据库检索数据,而无需使用额外的页面

时间:2019-12-11 17:31:36

标签: python html django django-models django-views

在我的“ django”项目中,我需要从(mysql)数据库的多个表中检索/插入数据。但是由于我使用的代码,我不得不为每个表操作使用一个额外的.html页面。我希望能够在单个html页面上访问多个表。为了更好地说明情况,我在下面编写了该项目的相关代码。

Project / views.py

def home_view(request, *args, **kwargs):
    print(args, kwargs)
    print(request.user)
    return render(request, "home.html", {})


@login_required()
def admin_view(request, *args, **kwargs):
    print(args, kwargs)
    print(request.user)
    return render(request, "adminPage.html", {})


@login_required()
def doctor_view(request):
    return render(request, 'doctorPage.html', {'doctors': doctor_view()})

appointments / views.py

from django.views.generic import DetailView, ListView


class list_of_appointments(ListView):

    model = Appointment
    template_name = 'appointments/appointment_list.html'


class list_of_patients(ListView):

    model = Patient
    template_name = 'appointments/patient_list.html'

约会/urls.py

urlpatterns=[
    url(r'^appointment_list/$', list_of_appointments.as_view(), name='list1'),
    url(r'^patient_list/$', list_of_patients.as_view(), name='list2')
]

因此,为了访问与表相关的操作,我必须使用以下网址代码。

<a href={% url 'appointments:list2' %}>

因此,我可以创建第二个html文件,并使用此方法从数据库中提取要提取的数据。

 {% for appointment in object_list %}


        <tr>

            <td>{{ appointment.patient.name }}</td>
            <td>{{ appointment.doctor.name }}</td>
            <td>{{ appointment.Date }}</td>
            <td>{{ appointment.time }}</td>
            <td>{{ appointment.province }}</td>
            <td><a href="#">
                <button type="button" class="btn btn-default"><span class="glyphicon glyphicon-pencil"
                                                                    aria-hidden="true"></span>Edit
                </button>
            </a></td>

        </tr>
    {% endfor %}

但是我想在现有的html链接(例如adminPage)上进行此数据库交互,而无需转到另一个链接。我无处可寻,该如何解决,您能帮我吗?谢谢大家!

1 个答案:

答案 0 :(得分:0)

如果要将多个模型传递给ListView,则可以覆盖get_context_data的{​​{1}}方法。但是要小心,它应该是MultipleObjectTemplateResponseMixin对象。该示例如下所示:

views.py

QuerySet

what-ever.html

from django.views.generic.list import ListView
from .models import FirstModel, SecondModel, ThirdModel

class MyListView(ListView):
    template_name = 'my_app/what-ever.html'
    model = Article

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['my_first_model'] = FirstModel.objects.all()
        context['my_second_model'] = SecondModel.objects.all()
        context['my_third_model'] = ThirdModel.objects.all()
        return context

您可以找到更多信息here