python - 从数据库中检索数据而不使用额外的页面
问题描述
在我的“django”项目中,我需要从我的(mysql)数据库的多个表中检索/插入数据。然而,由于我使用的代码,我不得不为每个表操作使用一个额外的 .html 页面。我希望能够在单个 html 页面上访问多个表。为了更好的说明情况,我把项目的相关代码写在下面。
项目/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()})
约会/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')
]
因此,为了访问与表相关的操作,我必须使用以下 url 代码。
<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)上进行此数据库交互,而无需转到另一个链接。我无处可以找到如何做到这一点,你能帮我吗?谢谢你们!
解决方案
如果您想将多个模型传递给ListView
,则可以覆盖get_context_data
的方法MultipleObjectTemplateResponseMixin
。但要小心,它应该是一个QuerySet
对象。该示例如下所示:
视图.py
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
what-ever.html
{% for object in my_first_model %}
<h1>{{ object.title }}</h1>
<p>{{ object.pk }}</p>
{% endfor %}
您可以在此处找到更多信息。
推荐阅读
- shiny - 有没有办法列出闪亮应用程序的对象(数据框、函数、参数(函数)、输入、输出
- python-3.6 - 如何使用python3创建一个指向一个外部hdf5文件的链接数组?
- r - 在R中的df中校正多年的值
- javascript - 为什么 String.fromCharCode() 没有返回正确的字符?
- selenium-webdriver - 如何爬取硒中的所有网页?
- android - firebase云函数错误TypeError:无法读取未定义的属性“子”
- php - 找不到类 'Dropbox\AppInfo' - PHP
- laravel - 如何在 laravel 中存储访客用户的身份?
- postgresql - 在 docker 中为链接数据库容器安装 pgadmin III
- datetime - 搜索可供预订的物品