How to get simple ForeignKey model working? (a list of class in another class)

54 Views Asked by At

I tried to figure this out on my own :( couldn't quite get there. Pls take pity. . .

I'm trying to represent exercise data (a start time an end time and many--an undetermined number of-- heart rates)

this is the model I have set up:

class HeartRate(models.Model):
    timestamp = models.DateTimeField('Date and time recorded')
    heartrate = models.PositiveIntegerField(default=0)
    def __str__(self):
        return prettyDate(self.timestamp)

class Exercise(models.Model):
    start_timestamp = models.DateTimeField('Starting time')
    finishing_timestamp = models.DateTimeField('Finishing time')
    heartrate = models.ForeignKey(HeartRate)

I know from working with the admin that it seems only one HeartRate is selected for each Exercise so maybe my approach is all wrong. How do I correctly model this? And once modeled correctly how do I query all heart rates for each (all) Exercises. I know this is a noob move but I really tried for hours getting this to work and can't quite get a handle on the documentation. Thanks in advance.

1

There are 1 best solutions below

1
On BEST ANSWER

You should reverse the foreign key relationship:

class HeartRate(models.Model):
    timestamp = models.DateTimeField('Date and time recorded')
    heartrate = models.PositiveIntegerField(default=0)
    exercise = models.ForeignKey(Exercise, related_name='heartrates')    

class Exercise(models.Model):
    start_timestamp = models.DateTimeField('Starting time')
    finishing_timestamp = models.DateTimeField('Finishing time')

To get all of the heartrates of an exercise:

heartrates = my_exercise.heartrates.all()