Django foreign key selection

Viewed 125

I am making a simple Django application that records the performance of running athletes. The models for the application look like this:

class Athlete(models.Model):
    name = models.CharField(max_length=30)
    nationality = models.CharField(max_length=30)

class TrainingSession(models.Model):
    training_date = models.DateTimeField()
    location = models.CharField(max_length=30)
    athlete = models.ForeignKey(Athlete)

class Run(models.Model):
    run_time = models.IntegerField()
    training = models.ForeignKey(TrainingSession)

An athlete has multiple training sessions and in each of those sessions, the athlete runs multiple times (each time, his time will be recorded in seconds).

I found out that I can easily make queries between these models, however, I still struggle with the following problem: I want to select the runners that CONSISTENTLY run between for example 20 and 30 seconds. When I select runners like this:

athletes = Athlete.filter(trainingsession__run__run_time__range=[20,30]).distinct()

I get all athletes that once ran between 20 and 30 seconds, but also athletes that once ran 35 seconds. Can you help me to solve this? Hopefully, there's a Django query that makes this easy!

2 Answers
Related