Django foreign key selection

I am making a simple Django application that records the performance of running athletes. The models for the application are as follows:

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)

      

The athlete has several training sessions, and in each of these sessions the athlete works several times (each time his time is recorded in seconds).

I found out that I can easily make queries between these models, however I am still struggling with the following problem: I want to select runners that WILL BE between 20 and 30 seconds. When I select runners like this:

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

      

I get all the athletes who once ran between 20 and 30 seconds, as well as the athletes who once ran 35 seconds. Can you help me solve this problem? Hopefully there is a Django request that makes this easy!

+3


source to share


2 answers


You can find another query for athletes who took commands <20

or >30

seconds and excluded them from the query set athletes

. you can use Q () to execute the query OR

.



excluded_athletes = Athlete.filter(Q(trainingsession__run__run_time__gte=30)|Q(trainingsession__run__run_time__lte=20)).distinct().values_list('id',flat=True)
athletes = Athlete.filter(trainingsession__run__run_time__range=[20,30]).distinct()
athletes.exclude(id__in=excluded_athletes)

      

+2


source


Objects

Q can help in making more complex queries: https://docs.djangoproject.com/en/1.11/topics/db/queries/#complex-lookups-with-q-objects

Perhaps something like this:



athletes = Athlete.filter(
    Q(trainingsession__run__run_time__gt=20) & 
    Q(trainingsession__run__run_time__lt=30)).distinct()

      

There are also some bugs in use .distinct()

. Order matters, and you can specify which fields are different. See Docs: https://docs.djangoproject.com/en/1.11/ref/models/querysets/#django.db.models.query.QuerySet.distinct

0


source







All Articles