我的模型来自postgres数据库。我从我的两个模型中获取数据以在浏览器中显示(CurrentAlLeagueStandings和CurrentNlLeagueStandings)。但是,我只能从一个模型中获取数据以便一次显示。如何让它在同一网页上同时显示每个模型的数据。当我尝试从一个模型中提取时,代码确实有效。需要注意的是,这两个模型都具有相同的字段名称。
如果有人能提供帮助,我们将不胜感激。一个与我的代码相关的例子将是一个巨大的帮助!
https://gist.github.com/anonymous/052b91ea56a951ac3fbc5ab7f66cc9f8
views.py
from django.shortcuts import render
from standings.models import CurrentAlLeagueStandings
from standings.models import CurrentNlLeagueStandings
def currentleaguestandings(request):
data = CurrentAlLeagueStandings.objects.all()
return render(request, 'standings/league.html', {"data": data})
data2= CurrentNlLeagueStandings.object.all()
return render(request, 'standings/league.html', {"data2": data2})
呈现的模板:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
#table to display data from CurrentAlLeagueStandings
<table>
<tr>
<th>Team Name</th>
</tr>
{% for standings in data %}
<tr>
<td>{{ standings.team }}</td>
</tr>
{% endfor %}
</table>
#table to display data from CurrentNlLeagueStandings
<table>
<tr>
<th>Team Name</th>
</tr>
{% for standings in data2 %}
<tr>
<td>{{ standings.team }}</td>
</tr>
{% endfor %}
</table>
</body>
</html>
答案 0 :(得分:1)
你可以做的是,你可以传递一个包含任意数量的数据变量的字典,你将模板渲染两次,这就是为什么你只能看到第二次渲染的数据:
def currentleaguestandings(request):
data = CurrentAlLeagueStandings.objects.all()
data2= CurrentNlLeagueStandings.objects.all()
return render(request, 'standings/league.html', {"data": data, "data2": data2})