You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django模板中如何简洁获取多对多关联子模型的Country ID列表

问题原因

{{ world_region.country.all.id }} 无法生效的核心原因是:world_region.country.all 返回的是 关联Country对象的QuerySet集合,不是单个Country实例,集合本身没有id属性,自然无法直接取值。

推荐解决方案

优先选模型加自定义方法的方案,符合Django的设计逻辑,性能最好,模板写法最简洁:

  1. 修改models.py中WorldRegion类,新增一个返回所有关联国家ID的方法:
    #parent
    class WorldRegion(models.Model):
        name = models.CharField(max_length=255)
        country = models.ManyToManyField(Country, blank=True)
    
        def __str__(self):
            return self.name
        
        def get_country_ids(self):
            # 仅查询id字段,性能远高于遍历全对象取id
            return list(self.country.values_list('id', flat=True))
    
  2. 模板中直接调用该方法即可,Django模板调用方法不需要加括号:
    {% for world_region in world_region_filters %}
    {{ world_region.name }} - {{ world_region.get_country_ids }}
    {% endfor %}
    
其他可选方案

如果不想修改模型,可以自定义模板过滤器实现批量取字段值:

  1. 在对应app下创建templatetags目录,新建custom_filters.py文件:
    from django import template
    register = template.Library()
    
    @register.filter
    def pluck(queryset, field_name):
        return list(queryset.values_list(field_name, flat=True))
    
  2. 模板中先加载自定义过滤器,再使用:
    {% load custom_filters %}
    {% for world_region in world_region_filters %}
    {{ world_region.name }} - {{ world_region.country.all|pluck:"id" }}
    {% endfor %}
    

你目前在用的逐一遍历写法虽然能实现效果,但会查询所有Country对象的全量字段,关联数据量大的时候性能很差,非必要不推荐使用。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.03 09:51:25