You need to enable JavaScript to run this app. Django类视图DetailView如何同时获取Log和关联Solutions模型数据渲染模板
优惠活动
大模型
产品
解决方案
定价
更多

Django类视图DetailView如何同时获取Log和关联Solutions模型数据渲染模板

实现方案

步骤1:(推荐)优化模型外键反向关联名

Django默认会为外键生成{小写模型名}_set的反向关联属性,为了调用更直观,可以给Solutions的log外键增加related_name参数,修改models.py中Solutions类的log字段:

class Solutions(models.Model):
    # 只需要修改这一行,增加related_name参数
    log = models.ForeignKey(
        Log, on_delete=models.CASCADE, blank=True, null=True, related_name="solutions")
    # 其余代码保持不变

修改后执行python manage.py makemigrations和python manage.py migrate同步数据库。

步骤2:改造DetailView注入关联数据(可选但推荐)

你可以选择直接在模板中调用反向关联属性,也可以重写视图的get_context_data方法提前把解决方案数据注入上下文,方便做排序、筛选等逻辑,同时可以通过预取关联数据优化查询性能,修改后的views.py代码如下:

class LogDetailView(DetailView):
    model = Log
    slug_url_kwarg = 'question'
    slug_field = 'slug'

    # 预取关联的解决方案,减少数据库查询次数
    def get_queryset(self):
        return super().get_queryset().prefetch_related("solutions")

    # 把解决方案注入模板上下文
    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        # 按创建时间倒序排列解决方案,最新的放在最前面
        context["solutions"] = self.object.solutions.all().order_by("-created")
        return context

如果不想修改模型加related_name,这里把self.object.solutions.all()换成self.object.solutions_set.all()即可。

步骤3:修改模板渲染解决方案列表

在log_detail.html中你想要展示解决方案的位置(比如Log详情下方、添加解决方案按钮上方)加入如下代码:

<!-- 解决方案列表开始 -->
<div class="solutions-container container mt-4 p-3">
  <h3>解决方案({{ solutions|length }}条)</h3>
  <hr>
  {% if solutions %}
    {% for sol in solutions %}
    <div class="solution-item card mb-3 p-3">
      <div class="d-flex align-items-center mb-2">
        <img class='rounded-circle account-img mr-2' src="{{ sol.author.profile.avatar.url }}" alt="" style="width:30px;height:30px;">
        <span>作者:<a href="{% url 'profile' sol.author %}">{{ sol.author }}</a></span>
        <span class="ml-3 text-muted">发布时间:{{ sol.created }}</span>
      </div>
      <p>{{ sol.solution }}</p>
      {% if sol.image %}
      <img style="width: 15vw" class="mt-2" src="{{ sol.image.url }}" alt="解决方案配图" />
      {% endif %}
    </div>
    {% endfor %}
  {% else %}
  <p class="text-muted">暂无解决方案,欢迎提交第一个解决方案~</p>
  {% endif %}
</div>
<!-- 解决方案列表结束 -->

如果你没有修改视图注入上下文,也可以直接在模板中遍历object.solutions.all或者object.solutions_set.all,把上面代码里的solutions换成对应的属性名即可。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.16 00:45:04