Django模板无法获取模型父对象字段?已用select_related仍失效
Django模板无法显示关联对象字段值的解决方案
问题场景
开发学生组队匹配界面时,使用select_related获取Potential模型关联的Profile父对象,控制台能通过values('user2__first_nm')打印出父对象字段值,但模板中使用match.user1__first_nm这类语法无法显示内容。
相关代码
模型代码
class Profile(models.Model): first_nm = models.CharField(max_length=100) last_nm = models.CharField(max_length=100) class Potential(models.Model): user1 = models.ForeignKey(Profile, related_name='user1', on_delete=models.CASCADE) user2 = models.ForeignKey(Profile, related_name='user2', on_delete=models.CASCADE)
视图代码
def matches(request): my_user = request.user my_id = Profile.objects.get(slug=my_user) the_matches = Potential.objects.filter(Q(user1=my_id) | Q(user2=my_id)).select_related('user1','user2') print(the_matches.values()) print(the_matches.values('user2__first_nm')) return render(request,'projects/matches_list.html', { 'matches':the_matches})
原模板代码
{% for match in matches %} <div class="matches"> <p>{{ match.user1__first_nm }}</p> <p>{{ match.user2__first_nm }}</p> </div> {% endfor %}
问题原因
Django的ORM查询中,双下划线__是跨关联表查询字段的语法,但模板语法里访问关联对象的属性需要使用点.,而非双下划线。模板里的match.user1__first_nm属于错误写法,无法正确解析关联对象的字段。
解决方法
修改模板代码,将双下划线替换为点.,直接通过关联对象访问字段:
{% for match in matches %} <div class="matches"> <p>{{ match.user1.first_nm }}</p> <p>{{ match.user2.first_nm }}</p> </div> {% endfor %}
视图中的select_related('user1','user2')已经正确预加载了关联的Profile对象,模板中通过match.user1.first_nm访问不会产生额外数据库查询,性能不受影响。
内容的提问来源于stack exchange,提问作者a.jones
相关产品推荐
相关产品推荐

