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

如何在Django中通过for循环遍历带数字后缀的模型字段?

Django动态遍历带数字后缀的模型字段

核心解决思路是利用Python内置的getattr()函数,动态拼接字段名并从模型实例中获取对应值,直接替换字段名里的数字后缀即可。

示例实现

1. 模型定义(参考你的结构)

# models.py
from django.db import models

class Bdc(models.Model):
    id_bdc = models.AutoField(primary_key=True)
    # 3组带数字后缀的字段
    bdc_index_line_1 = models.CharField(max_length=100)
    bdc_quantity_1 = models.IntegerField()
    bdc_index_line_2 = models.CharField(max_length=100)
    bdc_quantity_2 = models.IntegerField()
    bdc_index_line_3 = models.CharField(max_length=100)
    bdc_quantity_3 = models.IntegerField()

2. 视图中动态遍历字段

# views.py
from .models import Bdc

def your_view(request):
    # 获取目标模型实例(这里以第一个实例为例)
    bdc_obj = Bdc.objects.first()
    group_data = []
    
    # 遍历3组字段,计数器i从1到3
    for i in range(1, 4):
        # 动态拼接字段名,用getattr获取字段值
        index_line = getattr(bdc_obj, f'bdc_index_line_{i}', None)
        quantity = getattr(bdc_obj, f'bdc_quantity_{i}', None)
        
        # 把每组字段数据打包成字典,方便后续模板渲染
        group_data.append({
            'index': index_line,
            'quantity': quantity
        })
    
    return render(request, 'your_template.html', {'group_data': group_data})

3. 模板中渲染数据(可选)

<!-- your_template.html -->
{% for group in group_data %}
    <div>
        <h3>第{{ forloop.counter }}组数据</h3>
        <p>索引行:{{ group.index }}</p>
        <p>数量:{{ group.quantity }}</p>
    </div>
{% endfor %}

额外说明

  • getattr()的第三个参数None是默认值,当指定字段不存在时会返回该值,避免抛出属性不存在的异常。
  • 如果字段组数不固定,可以通过模型的_meta.get_fields()方法获取所有字段,再用正则匹配筛选出带数字后缀的字段:
import re
from .models import Bdc

# 匹配字段名规则:bdc_xxx_数字
field_pattern = re.compile(r'bdc_(.*)_(\d+)')
target_fields = [f.name for f in Bdc._meta.get_fields() if field_pattern.match(f.name)]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 22:07:07