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

Django错误:未找到匹配查询的Property,如何在Agent详情页展示其房产?

问题修正方案

你的代码错误在于误用了DetailView的get_queryset方法,同时参数获取逻辑也不正确,导致无法正确关联代理的房产数据。以下是修正步骤:

错误分析

  1. get_queryset方法在DetailView中的作用是筛选当前要展示的Agent实例,而非获取关联的Property数据,你错误地用它返回了Property查询集,导致系统无法找到匹配的Agent,触发报错。
  2. self.kwargs.get('agent')无法获取当前Agent实例,因为你的URL参数是slug,并非agent。

修正后的views.py代码

class AgentDetailView(DetailView):
    model = Agent
    template_name = 'blog/agent_detail.html'
    slug_field = 'slug'

    def get_context_data(self, **kwargs):
        # 继承父类的上下文数据(包含当前Agent实例)
        context = super().get_context_data(**kwargs)
        # 获取当前页面对应的Agent对象
        current_agent = self.get_object()
        # 将该代理发布的所有房产添加到上下文
        context['agent_properties'] = Property.objects.filter(agent=current_agent)
        return context

模板中展示房产数据

在blog/agent_detail.html中,通过上下文变量agent_properties遍历展示房产:

<!-- 代理信息部分保持不变 -->
<div class="agent-info">
    <h2>{{ object.name }}</h2>
    <!-- 其他代理信息渲染 -->
</div>

<!-- 新增代理房产展示部分 -->
<div class="agent-properties">
    <h3>该代理发布的房产</h3>
    {% for property in agent_properties %}
        <div class="property-item">
            <h4>{{ property.address }}</h4>
            <p>价格:{{ property.price }} 元</p>
            <p>卧室:{{ property.bedrooms }} | 浴室:{{ property.bathrooms }}</p>
            <!-- 根据需求渲染更多房产字段 -->
        </div>
    {% empty %}
        <p>该代理暂无发布的房产</p>
    {% endfor %}
</div>

这样就能在代理详情页同时展示代理信息和其发布的所有房产了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 02:33:13