我有Exercise
,Training
和Workout
的模型。
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
“锻炼”模型串行器。
有人可以提示我该怎么做吗?
答案 0 :(得分:0)
您可以通过以下方式对此进行查询:
Exercise.objects.filter(
trainings__workouts__name='workout'
)
使用连续的下划线(__
),您可以查找“通过”关系。
因此,这将返回名称为Exercise
的属于Training
的{{1}}的{{1}}。