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

Django使用外键获取关联项目集返回空查询如何解决?

问题原因
  • 你在games视图中使用type = Project_types(project_type='games')的写法,只是在内存中创建了一个全新的未保存的Project_types实例,没有从数据库读取你后台已经创建好的games分类记录
  • 该内存实例没有和数据库中已有的Projects记录建立关联,调用反向查询接口projects_set.all()必然返回空查询集
修复方案

首先修改views.py中的games视图逻辑,改为从数据库查询已存在的games分类:

from django.shortcuts import render, get_object_or_404 # 导入get_object_or_404用于安全查询
from .models import Project_types, Projects


def homepage(response):
    data = Project_types.objects.all()
    return render(response, 'main/homepage.html', {'project_types': data})


def hacks(response):
   return render(response, 'main/hacks.html', {'hacking_projects':"n"})

def games(response):
    # 从数据库查询project_type为games的已存在记录,不存在则返回404
    type = get_object_or_404(Project_types, project_type='games')
    t = type.projects_set.all()
    return render(response, 'main/games.html', {'gaming_projects': t})

如果需要在模板中逐条展示项目内容,可修改main/games.html的内容:

<!DOCTYPE html>
<html>
<head>
    <title>My Gaming Projects</title>
</head>
<body>
<header>My Gaming Projects</header>
{% for project in gaming_projects %}
<p>{{ project.project }}</p>
{% empty %}
<p>暂无游戏项目</p>
{% endfor %}
</body>
</html>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 01:36:07