gpt4 book ai didi

Django:基于注释进行注释

转载 作者:行者123 更新时间:2023-12-04 11:04:26 25 4
gpt4 key购买 nike

假设我正在使用 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 上的方法?非常感谢任何建议。

最佳答案

您可以使用这样的查询:

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")

关于Django:基于注释进行注释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19599043/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com