首页 > 解决方案 > Django:无法在模板内进行计算

问题描述

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

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}} 获得总收入,但不知何故我无法在模板中进行简单的减法。

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

标签: djangodjango-modelsdjango-viewsdjango-templates

解决方案


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

视图.py

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

推荐阅读