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

如何编写Django查询返回关联超过1个指定外键的对象?

Django 关联计数查询实现方案

首先需要导入Django ORM的聚合统计函数:

from django.db.models import Count

方案1:使用默认反向关联名查询(无需修改现有模型)

默认情况下,定义在Votes模型中的外键反向关联到People模型时,关联名称为votes_set,直接基于该字段做统计过滤即可:

# 返回所有关联Votes数量大于1的People查询集
result = People.objects.annotate(
    vote_count=Count('votes_set')
).filter(vote_count__gt=1)

方案2:自定义反向关联名优化查询可读性

如果需要频繁做这类关联查询,建议先修改Votes模型的外键字段,添加related_name参数自定义反向关联名(注意Django 2.0+版本外键必须指定on_delete参数,原代码缺失该配置):

class Votes(models.Model):
    value = models.CharField()
    people = models.ForeignKey(
        People, 
        on_delete=models.CASCADE, 
        related_name='votes' # 自定义反向关联名
    )

修改后查询语句可以简化为:

result = People.objects.annotate(
    vote_count=Count('votes')
).filter(vote_count__gt=1)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 21:06:04