BillB1951
BillB1951

Reputation: 225

How do I pass dissimilar data from view to template?

I am a relatively new to Django, and have just run into a wall, but I am sure this will be a cake walk for you veterans out there. I have a list of items I am displaying in a table in a template. That is no problem I create an object (list of values) in my view send it to the template and render the table. However, I would like to also show on my template a bunch of count()’s displayed as links, that when clicked will further filter the list of items displayed. For example, I may have items in the list that cost between $25 and $50, my link would show that there are say 20 items that match that criteria. When the link is selected in sends a request to the url.py that in turn executes a view that further filters the queryset then renders template again.

How do I get the count() info to the template? I do not think I can send two separate lists (objects) to the template (at least I have not been able to figure out how yet). I think I need to get the counts at the view and then somehow append them to my list object, but I’m not sure how to do that and also, not quite sure how to parse those values in the template. I want the counts to show separate from the table generated from my list object, and I am somewhat concerned I’m going to mess up my table that is working fine now.

I would appreciate any suggestions you have about how to tackle this, and I would really appreciate code examples because I am still somewhat Python/Django code challenged.

Upvotes: 1

Views: 115

Answers (2)

S.Lott
S.Lott

Reputation: 391952

Your requirements are vague. Code helps. Also. Periods to end sentences help.

I think I need to get the counts at the view and then somehow append them to my list object

how to parse those values in the template.

Here's an approach. It doesn't use aggregate functions. They are more efficient, but also a little more difficult to understand. https://docs.djangoproject.com/en/1.3/topics/db/aggregation/

You have something like this in your view:

object_list = Model.objects.filter( some_attribute=some_value )
    

You do this in your form to see a count.

{% for obj in object_list %}
    <tr><td>{{obj.name}}</td> <td>{{obj.related_set.count}}</td><tr>
{% endfor %}

This evaluates obj.related_set.count() for you. It's not the most efficient (aggregates are more efficient). But it's simple.

If you want a link, you'll replace the simple {{obj.related_set.count}} with something that includes a link

<a href="{% url "some.view.function" obj.id %}">{{obj.related_set.count}}</a>

Upvotes: 0

Daniel Roseman
Daniel Roseman

Reputation: 599778

You can send as many lists or objects to the template as you like. Template context is just a dictionary, and you can add items to it as necessary.

context = {
    'list1': my_first_list,
    'list2': my_second_list,
    ...
}

Upvotes: 3

Related Questions