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)
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
- [Django]-Django no sessionid in cookie
- [Django]-Shortening HTML content python / django
- [Django]-M2m 'through' field in django models throwing this error: 'M2M field' object has no attribute '_m2m_reverse_name_cache'
- [Django]-Foreign Keys clash with related field in Django Model
- [Django]-Complex reverse query in Django
Source:stackexchange.com