我的django项目是关于资金管理的,所以其中一种资金交易是 MultipleTransaction ,它只是说它是由多个用户共同制作的。< / p>
我想在我的界面中显示一个MultipleTransaction的总值,使用Django模板引擎,我该怎么做?
我尝试了以下内容:
template.html
{% with total=transaction.value*transaction.users.count %}
R${{ total }}
{% endwith %}
但我收到此错误消息:
/ historico /
中的TemplateSyntaxError无法解析余数:&#39; * transaction.users.count&#39;来自&#39; transaction.value * transaction.users.count&#39;
Model.py
# An abstract class containing info about a Transaction made by multiple users
class MultipleTransaction (Info):
# All users that paid the the monthly bill
users = models.ManyToManyField(User)
#A file as receipt, it can be an image or a pdf. This is optional
receipt = models.FileField(
'Comprovante(s)',
upload_to='comprovantes',
blank=True,
null=True
)
class Meta:
# Make this class an Abstract class
abstract = True
# Human friendly singular and plural name
verbose_name = 'Transação em Grupo'
verbose_name_plural = 'Transações em Grupo'
View.py
@login_required
def historico(request):
# Those 3 lines are queries of all transactions
deposits = chain(Deposit.objects.all(), MonthlyDeposit.objects.all())
withdraws = chain(Withdraw.objects.all(), EventSubscription.objects.all())
transferences = Transference.objects.all()
# Then all transactions are sorted by their atribute "created_at"
transactions = sorted(
chain(deposits,withdraws,transferences),
key=lambda instance: instance.created_at
)
# Get all boxes to show their values
boxes = Box.objects.all()
return render(
request,
'shell/app_shell.html',
{
'is_varys': True,
'transactions': transactions,
'boxes':boxes,
'title': 'Histórico'
}
)
答案 0 :(得分:3)
Django模板语言不支持乘法。您可以为模型添加方法。
class MultipleTransaction (Info):
# All users that paid the the monthly bill
users = models.ManyToManyField(User)
def calc_total_value(self):
return self.value * self.users.count()
R${{ transaction.calc_total_value }}
答案 1 :(得分:1)
您不能简单地将模板中的变量相乘。您必须编写自己的自定义模板标记以进行乘法,或者只是在模型侧进行计算。在模型中添加自定义方法来计算总交易价值是一个很好的方法。
答案 2 :(得分:0)
尝试
transaction.users.all().count
或者
transaction.all()[0].users.count