I'm writing a workout app and have a number of models that need to link together. Specifically, I have an Exercise model that needs to track the name of each exercise as well as the primary and secondary muscle groups targeted by the exercise. I also need a muscle group model, and these all need to link together in a ManyToMany fashion, e.g. any muscle group be associated with the primary and/or secondary or multiple exercises and vice versa.
How do I write the code to define the classes, as well as write a script to populate the database and test how to access various fields? Answered below to save others time. I spent way too long figuring this out.
First, define the models:
class Muscle(models.Model):
name = models.CharField(max_length=100)
class Exercise(models.Model):
name = models.CharField(max_length=100)
primary_muscles = models.ManyToManyField(Muscle, related_name="exercises_as_primary")
secondary_muscles = models.ManyToManyField(Muscle, related_name="exercises_as_secondary")
Next, write the script to add the data:
def add_data_to_database():
# Create new muscles for chest, shoulders, legs, and back as simple example.
chest = Muscle.objects.create(name="chest")
shoulders = Muscle.objects.create(name="shoulders")
legs = Muscle.objects.create(name="legs")
back = Muscle.objects.create(name="back")
# Create a new exercise called "bench press"
# that has "chest" as the primary muscle and "shoulders" as the secondary.
bench_press = Exercise.objects.create(name="bench press")
bench_press.primary_muscles.add(chest)
bench_press.secondary_muscles.add(shoulders)
# Create a new exercise called "deadlift"
# that has "back" as the primary muscle and "legs" and "shoulders" as the secondary muscles.
deadlift = Exercise.objects.create(name="deadlift")
deadlift.primary_muscles.add(back)
deadlift.secondary_muscles.add(legs, shoulders)
If we go to the django admin we can now see that we have two exercises created -- bench press and dealift -- as well as muscle groups created for chest, shoulders, legs, and back. Bench press only has one primary and one secondary muscle group associated with it, and deadlift has one primary and multiple secondary.
Lastly, the related name of "exercises_as_primary" or "exercises_as_secondary" is to reference the exercises if one is accessing them from the muscle group.
Hopefully this saves others with similar use cases some time!