[Answered ]-If / else in Django View

1πŸ‘

βœ…

you can override get_template_names, use cached_property for single query to the db

from django.utils.functional import cached_property

class RouteList(ListView):
    model = DailyRoute
    template_name = 'route_list.html'

    @cached_property
    def stage_exist(self):
        return DailyRoute.objects.filter( stage = '1').exists()

    def get_queryset(self):
        if self.stage_exist:
            query_set = DailyRoute.objects.filter(owner=employer, stage = '1').order_by('route')
        else:
            query_set = DailyRoute.objects.none()
        return query_set

    def get_template_names(self):
        return ['template 1.html'] self.stage_exist else ['template 2.html']

and read all comments, they are useful

πŸ‘€Brown Bear

1πŸ‘

get_queryset() should return a QuerySet object, so the solution is to return an empty QuerySet, which you can do with the none() function.

So returning DailyRoute.objects.none() should do it for template 2.

πŸ‘€mathew

0πŸ‘

If you’re sending nothing to the template, then you might as well use HttpResponseRedirect to redirect to template2 when condition is met.

Leave a comment