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

Django中如何过滤并展示Product关联的活跃ExternalProduct价格

问题原因

你出现的问题由两个错误共同导致:

  1. 方法定义位置错误:你将get_active_external_products方法写在了ProductDetailView视图类中,但模板里调用这个方法的product是Product模型的实例,不是视图类的实例,模板访问实例不存在的方法时默认返回空,因此没有数据也不会抛出报错。
  2. 查询语法错误:即使你将方法放到正确的位置,原写法self.external_products.objects.filter(active=True)也是错误的,关联管理器(related_name对应的管理器)本身自带filter方法,不需要额外加objects。

解决方法

提供两种常用实现方案,选一种即可:

方案1:给Product模型新增方法(推荐)

直接在Product模型中定义过滤方法,后续任意用到Product实例的场景都可以复用该逻辑:

class Product(models.Model):
    title = models.CharField(max_length=150)

    def __str__(self):
        return self.title
    
    # 新增过滤激活状态外部产品的方法
    def get_active_external_products(self):
        return self.external_products.filter(active=True)

模板部分不需要修改,原有的{% for ep in product.get_active_external_products %}逻辑可以直接生效。

方案2:在视图中注入过滤后的上下文

不需要修改模型,仅在详情页视图中把过滤好的外部产品列表加入模板上下文:

class ProductDetailView(DetailView):
    model = Product
    context_object_name = 'product'
    template_name = 'products/product_detail.html'

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        # 过滤当前产品的激活状态外部产品,加入上下文
        context['active_external_products'] = self.object.external_products.filter(active=True)
        return context

对应修改模板的遍历逻辑:

{% for ep in active_external_products %}
    <li>{{ ep.price }}</li>
{% endfor %}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 13:09:03