[Django]-Django foreign key selection

2👍

You can find one more queryset of athletes who ran in <20 or >30 seconds and exclude them from your athletes queryset. you can use Q()
to perform an OR query.

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)
👤badiya

0👍

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

Maybe something like this:

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

Also there are some gotchas when using .distinct(). Order plays a role, and you can specify what fields to distinct on.
See the docs: https://docs.djangoproject.com/en/1.11/ref/models/querysets/#django.db.models.query.QuerySet.distinct

Leave a comment