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

如何在Django中通过外键Subject过滤查询关联的Lecture数据

Django按Subject外键过滤Lecture数据实现方案

1. 修改视图层代码

首先调整你的views.py文件,代码如下:

from Diploma.models import Lecture, Subject
from django.shortcuts import render, get_object_or_404

# Create your views here.

def Diploma(request):
    return render(request, 'Diploma/diploma.html', context={
        'sub' : Subject.objects.all(),
    })

def Diploma_Subject(request, slug):
    # 先根据slug参数匹配到对应的Subject实例,找不到直接返回404
    target_subject = get_object_or_404(Subject, Slug=slug)
    return render(request, 'Diploma/subject.html', context={
        'subj' : Subject.objects.all(),
        # 过滤所有关联了当前Subject的Lecture数据
        'lect' : Lecture.objects.filter(Subject=target_subject),
        # 传给模板当前科目的信息,方便展示科目名称、封面等
        'current_subject': target_subject
    })

如果你不需要在模板中展示当前科目的额外信息,也可以直接通过外键关联字段过滤,省去单独查Subject的步骤:

'lect': Lecture.objects.filter(Subject__Slug=slug)

注意:必须严格对应你模型里的字段大小写,你定义的字段是Slug、Subject,不要写成小写的slug/subject,否则会触发字段不存在的报错。

2. 配置对应URL路由

在你的APP的urls.py中添加对应路由,确保slug参数能正确传入视图:

from django.urls import path
from . import views

urlpatterns = [
    path('', views.Diploma, name='diploma'),
    path('subject/<slug:slug>/', views.Diploma_Subject, name='diploma_subject'),
]

3. 模板层使用示例

科目列表页(diploma.html)跳转逻辑

遍历所有科目,添加跳转到对应课程列表页的链接:

{% for subject in sub %}
<div class="subject-card">
    <img src="{{ subject.Pic.url }}" alt="{{ subject.Title }}">
    <h3><a href="{% url 'diploma_subject' subject.Slug %}">{{ subject.Title }}</a></h3>
</div>
{% endfor %}

科目详情页(subject.html)展示课程

遍历过滤后的Lecture数据:

<h1>当前科目:{{ current_subject.Title }}</h1>
<div class="lecture-list">
{% for item in lect %}
    <div class="lecture-item">
        <h4>{{ item.Title }}</h4>
        <p>{{ item.More_Info }}</p>
        <!-- 其他视频、音频、文件字段按需展示 -->
    </div>
{% empty %}
    <p>该科目暂时没有上线课程</p>
{% endfor %}
</div>

可选优化建议

Django社区默认的模型字段命名规范为小写蛇形,比如title、slug、subject,你当前的大写开头字段虽然不影响功能运行,但容易和类名混淆,后续维护项目时可以统一调整为规范命名。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 14:48:05