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

Django多对多关联下按Account数量排序Course模型报错解决

解决Django按多对多关联数量排序Course模型的问题

首先修正你模型里的小错误:related_name参数需要传入字符串,你的代码里related_name=account_courses应该改为related_name='account_courses',否则会抛出变量未定义的错误。修正后的模型如下:

class Course(models.Model):
    name = models.CharField(blank=True, null=True)

class Account(models.Model):
    courses = models.ManyToManyField(Course, related_name='account_courses')

你之前用@property定义的course_accounts方法是在Python实例层面统计关联数量,Django ORM的order_by只能识别数据库字段或数据库层面聚合生成的字段,无法直接使用Python属性排序,这就是报错的原因。

正确的做法是用Django的聚合函数Count配合annotate,在数据库层面完成关联数量统计,再基于这个聚合字段排序:

升序排序

from django.db.models import Count

# 给每个Course对象添加account_count字段,统计关联的Account数量,再按该字段升序排序
courses = Course.objects.annotate(account_count=Count('account_courses')).order_by('account_count')

降序排序

如果需要按关联数量从多到少排序,只需在排序字段前加负号:

courses = Course.objects.annotate(account_count=Count('account_courses')).order_by('-account_count')

这样处理后,courses查询集里的每个Course对象都会带有account_count属性,既完成了排序,也能直接获取关联的Account数量,无需再用@property方法重复计算。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 10:33:29