Django:基于注释进行注释

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

假设我正在使用 Django 来管理有关运动员的数据库:

class Player(models.Model):
    name = models.CharField()
    weight = models.DecimalField()
    team = models.ForeignKey('Team')

class Team(models.Model):
    name = models.CharField()
    sport = models.ForeignKey('Sport')

class Sport(models.Model):
    name = models.CharField()

假设我想计算每支球队球员的平均体重。我想我会这么做:

Team.objects.annotate(avg_weight=Avg(player__weight))

但现在说我想计算每项运动中团队权重的方差。有没有办法使用 Django ORM 来做到这一点?在 QuerySet 上使用

extra()
方法怎么样?非常感谢任何建议。

django orm aggregate-functions
3个回答
0
投票

您可以使用这样的查询:

class SumSubquery(Subquery):
    template = "(SELECT SUM(`%(field)s`) From (%(subquery)s _sum))"
    output_field = models.Floatfield()
    def as_sql(self, compiler, connection, template=None, **extra_context):
        connection.ops.check_expression_support(self)
        template_params = {**self.extra, **extra_context}
        template_params['subquery'], sql_params = self.queryset.query.get_compiler(connection=connection).as_sql()
        template_params["field"] = list(self.queryset.query.annontation_select_mask)[0]
        sql = template % template_params
        return sql, sql_params



Team.objects.all().values("sport__name").annotate(variance=SumSubquery(Player.objects.filter(team__sport_id=OuterRef("sport_id")).annotate(sum_pow=ExpressionWrapper((Avg("team__players__weight") - F("weight"))**2,output_field=models.Floatfield())).values("sum_pow"))/(Count("players", output_field=models.FloatField())-1))

并将相关名称添加到模型中,如下所示:

class Player(models.Model):
    name = models.CharField()
    weight = models.DecimalField()
    team = models.ForeignKey('Team', related_name="players")

0
投票

我将假设(可能是错误的)你所说的“方差”是指最大和最小权重之间的差异。如果是这样,您可以使用单个查询生成多个聚合,如下所示:

from django.db.models import Avg, Max, Min

Team.objects.aggregate(Avg('player__weight'), Max('player__weight'), Min('player__weight'))

这取自 django 文档关于通过查询集生成聚合


0
投票

您可以尝试在团队内部使用@property

类似:

class Team(models.Mode):
    name = models.CharField()
    sport = models.ForeignKey('Sport')
    @property
    def avg_weight(self):
        list_of_weights = []
        for player in Player.objects.filter(Team = self):
            list_of_weights.append(player.weight)
            return sum(list_of_weights) / len(list_of_weights)
© www.soinside.com 2019 - 2024. All rights reserved.