[Answered ]-Django – Annotate within for loop – what is the difference between my two codes

1👍

Please don’t use .values(…). I wrote a short article that describes several problems with this [Django-antipatterns].

from django.db.models import F, Sum


def function(request, userprofile_id):
    profile = request.user.profile
    venue = profile.venue
    venues = Venue.objects.filter(itemised_loyalty_card__user=profile).annotate(
        total=Sum(
            F('itemised_loyalty_card__add_points')
            - F('itemised_loyalty_card__use_points')
        )
    )

    return render(
        request,
        'main/account/venue_loyalty_card.html',
        {
            'venue': venue,
            'venues': venues,
        },
    )

then in your template you enumerate over the venues and render the total:

{%for item in venues %}
    {{ item.name }}: {{ item.total }}
{% endfor %}

Note: Models in Django are written in PascalCase, not snake_case,
so you might want to rename the model from Itemised_Loyalty_Card to ItemisedLoyaltyCard.

Leave a comment