Django database filter in front end

Viewed 308

I have queries like following that I would like to implement it in front end:

MembershipPayment.objects.filter(group__name=tg.group_name).are_valid().count()
MembershipPayment.objects.filter(group__name=tg.group_name).Not_valid().count()

I know that I can pass this from view to front-end HTML, but the problem is that in the front end I have a query-set containing many "group"s. so I need to run a similar query for each of those "group"s.

I need something along these lines [this code of course won't work] in front:

        {% for rec in groups %}
            <tr>
                <td>{{ MembershipPayment.objects.filter(group__name=tg.group_name).are_valid.count }}</td>
                <td>{{ MembershipPayment.objects.filter(group__name=tg.group_name).not_valid.count }}</td>
            </tr>
        {% endfor %}

So I was wondering how can I achieve this without changing my model structure (if possible).

2 Answers

Why don't you do that logic in your view, by building a dict for each of your group, like:

def your_view(request):
    ...
    groups: dict = dict()
    for group_name in group_names:
        groups[group_name]: int = MembershipPayment.objects.filter(group__name=group_name).are_valid().count()
    return render(request,'your_template.html', {'groups': groups})

..and then pass it to your template, like:

{% for key, value in groups.items %}
<tr>
    <td>{{key}}</td>
    <td>{{value}}</td>
</tr>
{% endfor %}

...key being the group name, value being the group count.

I ended up passing a dictionary like this in view:

groups_statistics={group1:{monthly_balance:250,weekly_balance:3000},group2:{monthly_balance:250,weekly_balance:3000}}

and then looping through its value as:

{% for rec,stat_dic in groups_statistics.items %}
<tr>
         <td>{{ stat_dic.weekly_balance| get_value_from_dict:rec }}</td>
         <td>{{ stat_dic.monthly_balance| get_value_from_dict:rec }}</td>
</tr>
{% endfor %}

here get_value_from_dict is a customized tag defined in dictionarytags.py as:

from django import template
register = template.Library()

@register.filter('get_value_from_dict')
def get_value_from_dict(dict_data, key):
    """
    usage example {{ your_dict|get_value_from_dict:your_key }}
    """
    if key:
        return dict_data.get(key)

in the following folder:

my app>"templatetag" folder.

this folder contains: __ init __.py and dictionarytags.py and then in html I have this line in upper part:

{% load dictionarytags %}
Related