How to process data from one model field to another

Viewed 36

I have models of Exercise, Training and Workout.

Training contains some exercises (Exercise)

Workout contains trainings (Training).

Snippet of my 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.

I would also like to have possibility to use exercises`` field with Django Rest Framework to list all exercises, possibly with link to particularExercise``` model serializer.

Can someone give a hint how can I do that?

1 Answers

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 Exercises that belong to Trainings that belong to Workouts with as name 'Workout'.

Related