You need to enable JavaScript to run this app. Django如何在模板for循环中关联MySQL多表显示对应战队名称
优惠活动
大模型
产品
解决方案
定价
更多

Django如何在模板for循环中关联MySQL多表显示对应战队名称

解决方案

1. 调整models.py模型定义

首先新增对应league_clan表的模型,再修改LeagueMatch中的战队ID字段为外键关联,全程不会改动旧库表结构,完全兼容历史数据:

# 新增战队表模型,字段和表名要和实际旧库结构匹配
class LeagueClan(models.Model):
    idc = models.AutoField(primary_key=True) # 若战队表主键字段名不为id,替换为实际字段名
    name = models.CharField(max_length=100) # 替换为你实际存储战队名称的字段名
    # 其余战队表字段可按需补全
    class Meta:
        db_table = 'league_clan' # 明确指定对应旧表名,避免Django自动生成表名

# 修改原有LeagueMatch模型的idc1、idc2字段
class LeagueMatch(models.Model):
    objects = None
    idm = models.AutoField(primary_key=True)
    league = models.IntegerField()
    ids = models.PositiveIntegerField()
    judge = models.PositiveIntegerField()
    date = models.IntegerField()
    idg = models.PositiveIntegerField(blank=True, null=True)
    pos = models.IntegerField(blank=True, null=True)
    rnd = models.PositiveIntegerField(blank=True, null=True)
    # 替换原有的idc1、idc2整数字段为外键关联
    idc1 = models.ForeignKey(LeagueClan, on_delete=models.PROTECT, db_column='idc1', related_name='home_matches')
    idc2 = models.ForeignKey(LeagueClan, on_delete=models.PROTECT, db_column='idc2', related_name='away_matches')
    type = models.CharField(max_length=20, blank=True, null=True)
    idpt = models.PositiveSmallIntegerField()
    points1 = models.IntegerField()
    points2 = models.IntegerField()
    frags1 = models.SmallIntegerField()
    frags2 = models.SmallIntegerField()
    win1 = models.PositiveIntegerField()
    draw = models.PositiveIntegerField()
    win2 = models.PositiveIntegerField()
    maps = models.CharField(max_length=70)
    scores = models.CharField(max_length=70)
    descr = models.TextField()
    server = models.CharField(max_length=30)
    class Meta:
        db_table = 'league_match' # 建议明确指定旧表名避免异常

提示:如果存在idc1/idc2对应战队已被删除的脏数据,可将外键字段的on_delete参数改为models.SET_NULL,同时添加blank=True, null=True属性,查询时不存在的战队会显示为空,不会触发报错。

2. 优化views.py查询逻辑

使用select_related预加载关联的战队数据,避免模板循环时产生N+1次数据库查询,提升性能:

def all_matches(request):
    match_list = LeagueMatch.objects.select_related('idc1', 'idc2').all()
    return render(request, 'home_match.html',
                  {'match_list': match_list})

3. 调整模板代码展示战队名

将模板中原战队ID的位置替换为外键关联的战队名称字段即可:

{% for match in match_list reversed %}
{% if match.league == 1 %}
        <div class="card" >
              <div class="card-body">
                 <h5 class="card-title"><a href="{% url 'match-detail' match.pk %}"> Match  No {{ match.idm }} - Team A ({{ match.idc1.name }}) vs Team B ({{ match.idc2.name }})</a></h5>
                <p class="card-text"><b>Score : {{ match.win1 }} : {{ match.win2 }}</b></p>
              </div>
        </div>
        </br></br>
{% endif %}
{% endfor %}

如果你的league_clan表中存储战队名称的字段不为name,替换为实际字段名即可。

内容的提问来源于stack exchange,提问作者Tolga Yavuzer

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.19 15:24:01