diango admin 第三列为两列的乘积,如何计算

用户在前端输入数量和价格,能自动得出金额;
也就是金额=数据*价格

解决方法

使用template的乘法widthratio来实现
相当于 count /1 * price

Demo: table里显示数据,第三列自动为前两列的乘积

<td>{{  count }} </td>
<td>{{ price }} </td>
<td>{%  widthratio count  1  price %} </td>

如果要想两个都是输入框,第三列自动显示为两列的乘积,
那么,

在第一列、第二列加个 onChange函数,后边加个点击按钮触发事件,或者直接在第二列触发事件
函数内部进行着两个数的乘积和,最后显示在第三列上。

参考链接:


如有问题及时沟通

进来学习一下

def amount(self):
return %(self.price)*(self.number)
这样没反应


这是一种方法。不建议将模型字段命名为field_a或field_sum,但比仅使用a或sum好。在from django.db import models

class Example(models.Model):

VALUES = {

'AA': 1,

'AB': 3,

'AC': 2,

'BA': 1,

'BB': 3,

'BC': 2,

}

field_a = models.CharField(default='AA', max_length=2,)

field_b = models.CharField(default='BA', max_length=2,)

# The value in this field is derived from the first two.

# Updated every time the model instance is saved.

field_sum = models.PositiveIntegerField(

default=0, # This value will be overwritten during save()

editable=False, # Hides this field in the admin interface.

)

def save(self, *args, **kwargs):

# calculate sum before saving.

self.field_sum = self.calculate_sum()

super(Example, self).save(*args, **kwargs)

def calculate_sum(self):

""" Calculate a numeric value for the model instance. """

try:

value_a = self.VALUES[self.field_a]

value_b = self.VALUES[self.field_b]

return value_a * value_b

except KeyError:

# Value_a or value_b is not in the VALUES dictionary.

# Do something to handle this exception.

# Just returning the value 0 will avoid crashes, but could

# also hide some underlying problem with your data.

return 0

您可能需要阅读一些关于数据库设计和规范化的知识。在数据库中存储派生值通常不是一个好主意。在

如果在不使用Django ORM和save()方法的情况下更改值字典或更新表,则字段“u sum”中的值可能错误。在

保存所有实例将确保字段“_sum”正确。