[英]How to process data from one model field to another
I have models of Exercise
, Training
and Workout
.我有
Exercise
、 Training
和Workout
。
Training
contains some exercises ( Exercise
) Training
包含一些练习( Exercise
)
Workout
contains trainings ( Training
). Workout
包含培训 ( Training
)。
Snippet of my models.py:我的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)
...
I would like to have possibility to use something like Workout.objects.get(name='workout').exercises.objects.all()
to get a list/set of all exercises included in trainings of chosen Workout.我想有可能使用
Workout.objects.get(name='workout').exercises.objects.all()
来获取所选锻炼训练中包含的所有练习的列表/集。
I would also like to have possibility to use exercises`` field with Django Rest Framework to list all exercises, possibly with link to particular
Exercise``` model serializer.我还希望有可能在
exercises`` field with Django Rest Framework to list all exercises, possibly with link to particular
使用exercises`` field with Django Rest Framework to list all exercises, possibly with link to particular
练习```模型序列化程序的exercises`` field with Django Rest Framework to list all exercises, possibly with link to particular
。
Can someone give a hint how can I do that?有人可以提示我该怎么做吗?
You can query this with:您可以通过以下方式查询:
Exercise.objects.filter(
trainings__workouts__name='workout'
)
With the consecutive underscores ( __
), you thus can look "through" relations.使用连续的下划线 (
__
),您可以“透视”关系。
This will thus return the Exercise
s that belong to Training
s that belong to Workout
s with as name 'Workout'
.因此,这将返回属于
Training
s 的Exercise
s 属于名为'Workout'
Workout
s。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.