10

假设我正在使用 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 做到这一点?extra()在 QuerySet 上使用该方法怎么样?非常感谢任何建议。

4

2 回答 2

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")
于 2021-08-28T10:52:55.510 回答
0

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

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

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

这取自django docs on generate aggregation over a queryset

于 2022-02-28T03:36:50.013 回答