1👍
✅
Please don’t filter in the template: a template should only be concerned with rendering logic, not business logic.
You can prefetch in the view:
from datetime import date
from django.db.models import Prefetch
@login_required(login_url='/login')
def manage_business(request):
business = get_object_or_404(Business, owner=request.user)
employees = Employee.objects.filter(employer=business).prefetch_related(
Prefetch(
'time_set',
Time.objects.filter(
days=date.today().strftime('%A'), business=business
),
)
).select_related('user')
context = {'business': business, 'employees': employees}
return render(request, 'base/manage_business.html', context)
then we can render with:
{% for e in employees %}
<div class="employee-container">
<div class="flex-item" name="js-jobs">
<div class="main-text-container">
<h1 class="name">{{ e.user.name }}</h1>
{% for todaytime in e.time_set.all %}
<p class="employee-time">Today | {{ todaytime.start_time }} - {{ todaytime.finish_time }}</p>
{% empty %}
<p class="employee-time">Today | No Shift Assigned</p>
{% endfor %}
</div>
<div class="info-container">
<h3 class="info">Last Login | {{ e.user.last_login }}</h3>
<h3 class="info"><a id="assign-hours" href="#">Assign Hours</a></h3>
<h3 class="info">
<a id="delete-employee" href="#">Remove Employee</a>
</h3>
</div>
</div>
</div>
Source:stackexchange.com