2

我有和Exercise的模型。TrainingWorkout

Training包含一些练习 ( Exercise)

Workout包含培训 ( Training)。

我的models.py的片段:

class Exercise(models.Model):
    user = models.ForeignKey(User, related_name='exercises',
                             on_delete=models.CASCADE)
    name = models.CharField(max_length=80)
    description = models.TextField(max_length=300)
    details = models.ManyToManyField(ExerciseDetail, blank=True)
...


class Training(models.Model):
    user = models.ForeignKey(User, related_name='trainings',
                             on_delete=models.CASCADE)
    name = models.CharField(max_length=80)
    description = models.CharField(max_length=250)
    exercises = models.ManyToManyField(Exercise, related_name='trainings',
                                       blank=True)
...


class Workout(models.Model):
    user = models.ForeignKey(User, related_name='workouts',
                             on_delete=models.CASCADE)
    created_at = models.DateTimeField(auto_now=True)
    name = models.CharField(max_length=200)
    description = models.TextField(max_length=400, blank=True)
    trainings = models.ManyToManyField(Training, related_name='workouts',
                                       blank=True)
...

我希望有可能使用类似的东西Workout.objects.get(name='workout').exercises.objects.all()来获取包含在所选锻炼训练中的所有练习的列表/集。

我也想有可能使用exercises`` field with Django Rest Framework to list all exercises, possibly with link to particular练习```模型序列化程序。

有人可以提示我该怎么做吗?

4

1 回答 1

1

您可以通过以下方式查询:

Exercise.objects.filter(
    trainings__workouts__name='workout'
)

使用连续的下划线 ( __),您可以“看穿”关系。

因此,这将返回Exercise属于Trainings 的 s 属于Workouts 的 name 'Workout'

于 2019-07-02T12:25:27.897 回答