Django中完成join关联查询后如何访问关联模型的字段
问题根因
你已经通过select_related('locomotive_client')完成了关联查询,但模板中访问关联字段的路径错误:Locomotive模型本身不存在client_name字段,客户名称存储在外键locomotive_client指向的Client关联对象上,直接调用elements.client_name自然拿不到值。
修复方案
方案1:直接修正模板字段路径(改动最小)
只需要调整模板中关联字段的访问层级,先取外键对象,再取外键对象上的client_name属性即可,同时建议不要直接把模型对象作为option的value值,明确绑定需要提交的字段:
{% for locomotive in my_locomotives %} <option value="{{ locomotive.locomotive_number_id }}"> Locomotive N° {{ locomotive.locomotive_number_id }} - {{ locomotive.locomotive_client.client_name }} </option> {% endfor %}
渲染后就可以得到你预期的Locomotive N° 550XXXYYY - CUSTXXXYYY格式效果。
方案2:视图层扁平化查询(可选优化)
如果不需要在模板中用到Locomotive/Client模型的其他字段,可以直接在视图层用values提取需要的字段,减少冗余数据传递:
- 修改
views.py中的查询逻辑:
def settings(request): my_clients = Client.objects.values_list('client_name', flat=True) my_locomotives = Locomotive.objects.select_related('locomotive_client').values( 'locomotive_number_id', 'locomotive_client__client_name' ) return render(request, 'home/settings.html', context={ "my_clients": my_clients, "my_locomotives": my_locomotives })
- 对应模板调整为:
{% for item in my_locomotives %} <option value="{{ item.locomotive_number_id }}"> Locomotive N° {{ item.locomotive_number_id }} - {{ item.locomotive_client__client_name }} </option> {% endfor %}
说明:你打印的SQL语句已经能查到关联的
client_name字段,说明ORM关联逻辑本身没有问题,只是Django ORM会自动把关联表的字段挂载到对应的外键属性下,不会直接平铺到主表模型实例上。
内容的提问来源于stack exchange,提问作者Ridha Kchouk
相关产品推荐
相关产品推荐

