如何在 Django 中为特定用户查找 ForeignKey 字段的最大值

How to find the highest value of a ForeignKey field for a specific user in Django

我正在构建一个允许用户记录他们锻炼的应用程序。首先,他们将创建一个练习(例如卧推),然后他们将填写一个表格以显示他们在该特定练习中能够举起多少重量。他们的结果将显示在表格下方。将有许多锻炼形式,涉及许多不同的锻炼。锻炼和练习也将针对每个用户。

这是我的 models.py:

from django.contrib.auth.models import User

class Exercise(models.Model):
    name = models.CharField(max_length=100)

class Workout(models.Model):
    user = models.ForeignKey(Profile, on_delete=models.CASCADE)
    weight = models.DecimalField(default=0.0, max_digits=5, decimal_places=1)
    exercise = models.ForeignKey(Exercise, on_delete=models.CASCADE, default=None)

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)

我现在想做的是能够向用户显示他们在每次不同锻炼中的最大举升力是多少,但无法弄清楚如何检索此信息。我在网上搜索了答案,似乎使用 aggregate 或 annotate 可能是可行的方法,但我尝试了一堆不同的查询,但无法显示我需要的内容。希望有人能帮忙。

给定一个用户,您需要用最大重量注释每个练习。

from django.db.models import Max

user.workout_set.values('exercise').annotate(max_weight=Max('weight'))

这应该有效

不使用聚合,一种简单的方法是排序,然后在练习中使用 distinct:

Workout.objects.filter(user=user)\
    .order_by('exercise', '-weight')\
    .distinct('exercise')

这将为您提供所有锻炼的列表,每个锻炼的重量最大。

您可以使用给定用户的 Workout 的最大权重注释您的 Exercise

from django.db.models import Max

Exercise.objects.filter(
    workout__user=<i>someprofile</i>
).annotate(
    <b>max_weight=Max('workout__weight')</b>
)

this 查询集产生的 Exercise 对象将有一个额外的属性 .max_weight,其中包含该练习的最大权重 someprofile.