如何在 Django ORM 中通过最大值获取对象

问题描述 投票:0回答:1

我正在寻找一种更好的方法来做到这一点:我需要获取模型中具有最高值的对象。

该值不存储在字段中,而是来自相关(辅助)模型(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>

这个变体效果很好,但我想知道,有没有更好的方法来做到这一点?

python django django-models orm
1个回答
0
投票

只需按注释订购商品即可:

from django.db.models import Count

annotatedPM = PrimaryModel.objects.annotate(Count('secondarymodel')).order_by(
    '-secondarymodel__count'
).first()
© www.soinside.com 2019 - 2024. All rights reserved.