I have the following custom QuerySet method for a model called Program:
def with_volunteer_stats(self):
from programs.models import Session
volunteers_needed = ExpressionWrapper(
F('num_student_seats') / F('student_volunteer_ratio'),
output_field=models.IntegerField())
sessions = (
Session.objects.filter(program_id=OuterRef('pk'))
.annotate(num_volunteers=Count('volunteer_attendances__volunteer', distinct=True))
.order_by('num_volunteers')
)
qs = self.annotate(
volunteers_needed=volunteers_needed,
least_volunteers=Subquery(sessions.values('num_volunteers')[0])
).annotate(
remaining_volunteers_needed=(F('volunteers_needed') - F('num_volunteers'))
)
return qs
When running this, I get the exception:
ValueError: This queryset contains a reference to an outer query and may only be used in a subquery.
The traceback shows the exception occurring on the evaluation of the line using Subquery. This is very close to the example in the Django documentation on how to use Subquery. Any ideas what I'm doing wrong?