Maquisard
Maquisard

Reputation: 83

Accessing variable context name in template

I'm just discovering Django and i'm still a total noob.

I got a view that return multiple query set.

class RouteDateView(ListView):
   model = Tblsummary
   template_name = 'reviewrouteassess/selectdaterange.html'

   def get_context_data(self, *args, **kwargs):
       context = super(RouteDateView, self).get_context_data(*args, **kwargs)

       context['allroute'] = Tblsummary.objects.filter(off_no=self.request.GET.get('depotcode')[:4])

       for p in context['allroute']:
          context[p.res_route] = Tblsummary.objects.filter(res_route=p.res_route)

       return context    

Then in my template I would like to access those dynamically name context. That's where i'm stuck.

<table>
{% for a in allroute %}
    <tr>
        <td>{{ a.res_route }}</td>
        <td>{{ a.hcalls }}</td>
    </tr>
    {% for d in a.res_route %}
        <tr>
            <td>{{ d.res_route }}</td>
            <td>{{ d.hcalls }}</td>
        </tr>
    {% endfor %}
{% endfor %}

How can I evaluate a.res_route so that a.res_route return the context passed by the view?? Thanks you so much!!

{% for d in a.res_route %}

Upvotes: 0

Views: 111

Answers (1)

azundo
azundo

Reputation: 6052

I would suggest adding a method to your model to access the second query:

class Tblsummary(models.Model):
    ... # or whatever is there currently

    def sub_routes(self):  # name this how you'd like
        return Tblsummary.objects.filter(res_route=self.res_route)

And then in your template:

<table>
{% for a in allroute %}
    <tr>
        <td>{{ a.res_route }}</td>
        <td>{{ a.hcalls }}</td>
    </tr>
    {% for d in a.sub_routes %}
        <tr>
            <td>{{ d.res_route }}</td>
            <td>{{ d.hcalls }}</td>
        </tr>
    {% endfor %}
{% endfor %}

This isn't going to be ideal from an efficiency standpoint since the sub_routes query is called once per entry in allroute but right now allroute is limited to 4 results so that shouldn't be an issue in practice.

Upvotes: 1

Related Questions