我正在尝试重建最初用php编写为django的网站。我是django的新手。我停留在一些相当基本的功能上,但是在任何地方都找不到答案,所以我在这里问。
我正在建立一个幻想棒球场。我有以下2种型号:
class IbcDivisions(models.Model):
division = models.AutoField(primary_key=True)
div_abbr = models.CharField(unique=True, max_length=255)
div_name = models.CharField(max_length=255)
league = models.ForeignKey('IbcLeagues', models.DO_NOTHING,
db_column='league')
class Meta:
managed = False
db_table = 'ibc_divisions'
class IbcLeagues(models.Model):
league = models.AutoField(primary_key=True)
league_abbr = models.CharField(max_length=255)
league_name = models.CharField(max_length=255)
class Meta:
managed = False
db_table = 'ibc_leagues'
这些表提供以下数据(如果您遵循棒球,将会得到什么):
IbcLeagues:
league league_abbr league_name
1 AL American League
2 NL National League
IbcDivisions:
division div_abbr div_name league
1 ALE AL East 1
2 ALC AL Central 1
3 ALW AL West 1
4 NLE NL East 2
5 NLC NL Central 2
6 NLW NL West 2
我已经在views.py中找到了这段代码:
def homepage(request):
ibc_leagues = IbcLeagues.objects.all()
context = {
'ibc_leagues' : ibc_leagues,
}
return render(request, 'ibc_leagues/index.html', context)
我有一个提供index.html的布局页面。 Index.html具有以下代码:
{% extends 'ibc_leagues/layout.html' %}
{% block content %}
<h2>Rosters</h2>
{% for ibcl in ibc_leagues %}
<h3>{{ibcl.league_name}}</h3>
{% endfor %}
{% endblock %}
所有有效,太好了。它产生:
最后,我的问题:如何在每个联赛的下方循环显示每个分区(AL东,中,西)?
答案 0 :(得分:1)
您正在途中。要访问父模型实例的子代,请使用modelname_set
语法。例如:
{% for ibcl in ibc_leagues %}
<h3>{{ibcl.league_name}}</h3>
{% for division in ibcl.ibc_divisions_set.all %}
<h4>{{ division.div_abbr }}: {{ division.div_name }}</h4>
{% endfor %}
{% endfor %}