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

Django按字段值筛选对象?关联查询查询集为空问题排查

问题分析与解决方案

模型定义中的笔误修正

你的Video模型存在两处关键错误,直接影响数据关联与查询逻辑:

  1. 外键关联的模型名称写错,应改为article而非at:
    # 修正前
    article = models.ForeignKey(at, on_delete=models.CASCADE)
    # 修正后
    article = models.ForeignKey(article, on_delete=models.CASCADE)
    
  2. __str__方法引用了不存在的self.at,需改为self.article:
    # 修正前
    def __str__(self):
        return str(self.title) + " - " + str(self.at)
    # 修正后
    def __str__(self):
        return str(self.title) + " - " + str(self.article)
    

修正后执行数据库迁移命令,确保模型变更生效:

python manage.py makemigrations
python manage.py migrate

修正查询语句

你当前使用的at__slug=slug是错误的,因为Video模型的外键字段名为article,正确的查询条件应为:

def article(request, slug):
    videos = models.Video.objects.filter(article__slug=slug)
    return render(request, 'videos/at_detail.html', {'videos': videos})

验证数据库数据一致性

通过Django Shell确认数据是否符合预期:

  1. 启动Shell:
    python manage.py shell
    
  2. 检查目标article实例是否存在:
    from your_app.models import article, Video
    # 替换your_app为你的实际应用名
    target_article = article.objects.filter(slug='blueberry').first()
    print(target_article)  # 输出None则表示无对应记录
    
  3. 如果存在目标article,检查关联的Video数据:
    related_videos = Video.objects.filter(article=target_article)
    print(related_videos)
    
  4. 确认URL输入的slug与数据库中article的slug完全一致(AutoSlugField默认生成小写slug,注意大小写匹配)。

额外排查点

若之前因模型错误导致Video数据未正确关联到article实例,需重新创建关联正确的Video记录,确保每条Video的article字段都指向有效的article对象。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 08:50:22