我之前问过这个问题,但我没有收到任何解决方案,所以这次我试图让问题更简洁明了。
我的数据库具有以下简化架构:
class RIAchievement(models.Model):
riAchievementID = models.AutoField(primary_key=True, db_column="riAchievementID")
userLanguageVersionID = models.ForeignKey(UserLanguageVersion, db_column="userLanguageVersionID", related_name="riAchievement_userLanguageVersionID")
class Meta:
db_table="riAchievement"
class UserLanguageVersion(models.Model):
userLanguageVersionID = models.AutoField(primary_key=True, db_column="userLanguageVersionID")
languageCodeID = models.ForeignKey(LanguageCode, db_column="languageCodeID", related_name="userLanguageVersion_languageCodeID")
class Meta:
db_table="userLanguageVersion"
class LanguageCode(models.Model):
languagecodeID = models.AutoField(primary_key=True, db_column="languageCodeID")
class Meta:
db_table="languageCode"
class Flag(models.Model):
flagID = models.AutoField(primary_key=True, db_column="flagID")
languageCodeID = models.ForeignKey(LanguageCode, db_column="languageCodeID", related_name="flag_languageCodeID")
flagIconPath = models.CharField(max_length=255, db_column="flagIconPath")
class Meta:
db_table="flag"
本质上, riachievement 可以有很多 userlanguageversion , userlanguageversion 可以有很多 languagecode , flag 可以有很多 languagecode 。
使用select_related不会返回flag.flagIconPath因为一对多的关系,所以 Django 文档状态我必须使用prefetch_related,并带有一对多外键的相关名称。
所以我在view.py中修改了我的代码:
from django.shortcuts import render
from app_data.models import RIAchievement
def ri_achievements(request):
qs = RIAchievement.objects.select_related("riachievement", "userlanguageversion", "languagecode", "flag_languageCodeID").all()
return render(request, 'index.html',{'qs': qs})
我的index.html:
{% for ri_achievement in qs %}
{{ ri_achievement.userLanguageVersionID.langaugeCodeID.flag_languageCodeID.flagIconPath }}
{% endfor %}
但是,这段代码什么也不返回。
谁能提供一些建议,因为我看不到我做错了什么?