简体   繁体   中英

Summarizing values for each row in a table dynamically generated from django context variables

So I have the following table in my template:

<tbody>
        {% for user in users %}
            <tr>
                <td>{{ user.title }} </td>
                {% for fruit in fruits %}
                    {{ sum|add:user|get_attr:fruit }}
                        <td>{{ user|get_attr:fruit }} </td>
                {% endfor %}
                {% for vegetable in vegetables %}
                    {{ sum|add:user|get_attr:vegetable }}
                        <td>{{ user|get_attr:vegetable }} </td>
                {% endfor %}
            <td>{{ sum }}</td>
        {% endfor %}
</tbody>

"fruits" and "vegetables" are lists passed as context from the view. The following custom filter allows me to iterate through those lists extract integer values from the model "user". The table columns are generated the same way, so this filter has to be in the table:

@register.filter
def get_attr(obj, attr):
    return getattr(obj, attr)  

The variable "sum" is passed as context from the view with the value 0. I'm trying to make it summarize all the relevant row variables in the template, but it remains 0. As far as I can see there are three ways I could go about this:

  1. Solve this in the template (as I'm trying now)
  2. Generate the value in the view (although I have no idea how I would go about this)
  3. Add some JS to solve it (would prefer to avoid this).

How should I go about solving this?

Solved this on the back end by generating a dictionary:

views.py

sum = {}
for user in users:
    identity = user.pk
    score = 0
    all_food = fruits + vegetables
    for food in all_food:
        score += getattr(user,food)
    sum[identity] = score

The summarized value can now be accessed in the template by using another custom template tag:

@register.filter
def get_value(dictionary, key):
    return dictionary.get(key)

Adding it to the template:

{{ sum|get_value:user.pk }}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM