Django:无法在模板内进行计算

Django: unable to make a calculation inside a template

我创建了一个电子商务 Django 应用程序,在这个应用程序的后台,我有一个页面应该显示一些统计信息。 我正在尝试显示收益或损失。 对于成本,我在模型中创建了一个@属性,如下所示:

class Statistics(models.Model):
    """
    The Statistics model represents the statistics that can be calculated
    """
    costs_infra = models.FloatField(verbose_name="Costs Infrastructure")
    costs_salary = models.FloatField(verbose_name="Costs Salary")

    class Meta:
        verbose_name_plural = "Statistics"   

    def __str__(self):
        """Unicode representation of Statistics"""

        return " Infra costs: {}, Salary costs: {}".format(
                self.costs_infra,
                self.costs_salary
            )
    
    @property
    def calculate_costs(self):
        return self.costs_infra + self.costs_salary

对于总收入,我在视图中计算如下:

@group_required('Administrator', 'Manager')
def stats_home(request):

    total_users = User.objects.all().count()
    costs = Statistics.objects.all()
    subscriptions_1month = Subscription.objects.get(plan_name='1 Month')
    subscriptions_1year = Subscription.objects.get(plan_name='1 Year')
    subscriptions_3year = Subscription.objects.get(plan_name='3 Years')
    user_subscriptions_1month = UserSubscription.objects.filter(subscription=subscriptions_1month).annotate(Count('user', distinct=True)).count()
    user_subscriptions_1year = UserSubscription.objects.filter(subscription=subscriptions_1year).annotate(Count('user', distinct=True)).count()
    user_subscriptions_3years = UserSubscription.objects.filter(subscription=subscriptions_3year).annotate(Count('user', distinct=True)).count()

    income_per_subscription_1month = Subscription.objects.get(plan_name='1 Month').price * UserSubscription.objects.filter(subscription=subscriptions_1month).count()
    income_per_subscription_1year = Subscription.objects.get(plan_name='1 Year').price * UserSubscription.objects.filter(subscription=subscriptions_1year).count()
    income_per_subscription_3years = Subscription.objects.get(plan_name='3 Years').price * UserSubscription.objects.filter(subscription=subscriptions_3year).count()
    
    total_income = income_per_subscription_1month + income_per_subscription_1year + income_per_subscription_3years

    return render (request, "stats_home.html", locals())

最后,我正在尝试进行一个简单的计算(总收入 - 总成本),但我无法在模板内执行此操作,据我所知和我的研究。

{% extends 'base.html' %}
{% load crispy_forms_tags %}
{% load has_group %}

{% block title %} Statistics Home {% endblock %}

{% block content %}

    <div class="card border-dark mb-4" id="profil">
        <h5 class="card-header bg-dark text-white">Total number of users subscribed to the site:</h5>
        <div class="card-body">
         {{total_users}}
        </div>
    </div>

    <div class="card border-dark mb-4" id="profil">
        <h5 class="card-header bg-dark text-white">Total number of users per subscription type:</h5>
        <div class="card-body">
        <br>1 Month: {{user_subscriptions_1month}}
        <br>1 Year: {{user_subscriptions_1year}}
        <br>3 Years: {{user_subscriptions_3years}}
        </div>
    </div>

    <div class="card border-dark mb-4" id="profil">
        <h5 class="card-header bg-dark text-white">Costs:</h5>
        <div class="card-body">
            {% for cost in costs %}
            <p>Infrastructure Costs: {{cost.costs_infra}}</p>
            <p>Salary Costs: {{cost.costs_salary}}</p>
            <p>Total Costs: {{cost.calculate_costs}}</p>
            {% endfor %}
        </div>
    </div>

    <div class="card border-dark mb-4" id="profil">
        <h5 class="card-header bg-dark text-white">  Total Income: </h5>
        <div class="card-body">
          {{total_income}}
        </div>
    </div>

    <div class="card border-dark mb-4" id="profil">
        <h5 class="card-header bg-dark text-white">  Benefits/Loss: </h5>
        <div class="card-body">
            Benefits/Loss: {{total_income - cost.calculate_costs}}
        </div>
    </div>

通过执行 {{total_income - cost.calculate_costs}} 我得到一个错误

无法解析余数:来自 'total_income - cost.calculate_costs'

的“-cost.calculate_costs”

问题是我可以用 {{cost.calculate_costs}} 得到总成本,用 {{total_income}} 得到总收入,但不知何故我无法做一个简单的模板内的减法。

实现此目标的最佳方法是什么?

你能做的最好的事情是,不要在模板中进行计算,而是在视图中进行计算,因为它是 建议不要在模板中进行计算,因为它会 降低网站的性能 改为这样做:

views.py

variable = total_income - total_costs
context = {"variable":variable}
return render(request, "stats_home.html", locals(), context)

您的问题是您正试图在循环 {% for cost in costs %} 之外访问 cost.calculate_costs。由于 cost 未声明,您会收到此错误。最重要的是,django 本身不支持模板中的计算——原因是最好将逻辑完全保留在视图中,而只在模板中保留表示。然而有addition filter,但你仍然需要计算total_costs

您的解决方案是计算 total_profit 在视图中:

def stats_home(request):
    ...
    total_costs = sum(cost.calculate_costs for cost in costs)
    total_profit = total_income - total_costs

    return render (request, "stats_home.html", locals())
<div class="card border-dark mb-4" id="profil">
    <h5 class="card-header bg-dark text-white"> Benefits/Loss: </h5>
    <div class="card-body">
        Benefits/Loss: {{ total_profit }}
    </div>
</div>