我正在寻找一种更好的方法:我需要得到一个模型中具有最高值的对象。
该值不存储在字段中,而是来自相关(辅助)模型的多个对象(ManyToOne关系,ForeignKey)
我试过了:
from django.db.models import * annotatedPM = PrimaryModel.objects.annotate(Count('secondarymodel')) max_value = annotatedPM.aggregate(Max('secondarymodel__count'))['secondarymodel__count__max'] annotatedPM.get(secondarymodel__count=max_value) >>> <PrimaryModel: object>
这种变体效果很好,但我想知道,有更好的方法吗?
只需按注释对项目进行排序:
from django.db.models import Count annotatedPM = PrimaryModel.objects.annotate(Count('secondarymodel')).order_by( '-secondarymodel__count' ).first()
甚至更短 .latest(â¦)  [Django-doc] :
.latest(â¦)
from django.db.models import Count annotatedPM = PrimaryModel.objects.annotate(Count('secondarymodel')).latest( 'secondarymodel__count' )
如果没有,这将引发一个错误 PrimaryModel 记录在整个表格中。
PrimaryModel