1👍
✅
Please don’t do this in the template. Templates should be used to implement rendering logic, not business logic. Templates are not very efficient, but also deliberately lack all sorts of tooling to prevent people from doing this.
You can use an Exists
subquery to check this, this will also boost efficiency:
from django.db.models import Exists, OuterRef
class PersonPageView(DetailView):
model = Person
queryset = Person.objects.prefetch_related(
Prefetch('jobs_set', Jobs.objects.select_related('jobnumber')),
Prefetch('crew_set', Crew.objects.select_related('person')),
).annotate(
is_supervisor=Exists(
Crew.objects.filter(person_id=OuterRef('pk'), role='Supervisor')
)
)
template_name = '_person_info.html'
The person
will then have an extra attribute .is_supervisor
, so you can use:
{% if person.is_supervisor %}
…
{% endif %}
Source:stackexchange.com