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

Django Referral系统查询下线关联模型模板循环报错求助

问题原因
  • 核心错误1:视图函数中context定义和return render逻辑写在了for my in my_ref循环内部,第一次遍历到下线用户就直接返回了响应,只传递了单个TheMain对象ma到模板,且提前终止了后续所有下线数据的收集
  • 核心错误2:模板中使用{% for r in ref %}循环遍历单个TheMain对象,自然触发object is not iterable的类型错误
  • 冗余问题:视图中定义的全局变量完全无使用必要,Referral模型的get_referred方法全表遍历效率极低,存在性能隐患
修复方案

1. 优化视图函数

将context定义和响应返回逻辑移出循环,传递收集好的完整refer_main列表到模板,同时删除无用的全局变量声明:

def referral_page(request, *args, **kwargs):
    referral = Referral.objects.get(user=request.user)
    my_ref = referral.get_referred()

    refer_main = []
    refer_invest =[]
    for my in my_ref:
        # 因为TheMain和User是OneToOne关系,直接用get不用filter遍历
        ma = TheMain.objects.get(user = my.user)
        refer_main.append(ma)
        print(f'this is the mama {ma} and amount funded{ma.main_balance}')
    
    # 注意缩进:把context和return放到for循环外面
    context = {
        'ref_list': refer_main  # 命名更清晰,传递的是列表
    }
    return render(request, 'referral/referral.html', context)

2. 优化Referral模型的get_referred方法(性能优化,非必须但强烈建议)

避免全表扫描,直接使用ORM过滤:

def get_referred(self):
    # 直接过滤referred_by等于当前用户的Referral对象,效率提升明显
    return Referral.objects.filter(referred_by=self.user)

3. 调整模板代码

遍历列表,同时补全表格的行结构,对应展示需要的字段:

<table class="table table-striped table-bordered no-margin ">
    <thead>
        <tr class="bg-pale-dark">
            <th class="text-center border-top-0">Username</th>
            <th class="text-center border-top-0">Account Status</th>
            <th class="text-center border-top-0"> Date Registered</th>
            <th class="text-center border-top-0">User's Investment</th>
            <th class="text-center border-top-0">Investment Status</th>
            <th class="text-center border-top-0">Ref Bonus</th>
        </tr>
    </thead>
    <tbody>
        {% for r in ref_list %}
        <tr>
            <td class="text-center">{{ r.user.username }}</td>
            <td class="text-center">{{ r.user.is_active|yesno:"激活,未激活" }}</td>
            <!-- 注册日期取User的date_joined或者Referral的created字段都可以 -->
            <td class="text-center">{{ r.user.date_joined|date:"Y-m-d" }}</td>
            <td class="text-center">{{ r.main_balance }}</td>
            <!-- 投资状态后续关联对应投资模型补充字段即可 -->
            <td class="text-center">待补充</td>
            <td class="text-center">待补充</td>
        </tr>
        {% empty %}
        <tr>
            <td colspan="6" class="text-center">暂无邀请的下线用户</td>
        </tr>
        {% endfor %}
    </tbody>
</table>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 08:48:03