django - 如何在 django 中使用模板过滤器访问反向外键单个字段的总和?
问题描述
假设我有 2 个模型客户和帐户。
楷模
class Account(models.Model):
customer = models.ForeignKey(Customer,on_delete=models.CASCADE,
blank=True,null=True,related_name='account')
desc = models.CharField(max_length=100)
paid = models.IntegerField(default=0)
received = models.IntegerField(default=0)
created_at = models.DateTimeField(auto_now_add=True)
class Customer(models.Model):
name = models.CharField(max_length=30,unique=True)
contact = models.CharField(max_length=10)
我想访问模板中收到的总和和已付字段的总和
客户视图
def show_customer(request,id=None):
customer = Customer.objects.filter(user=request.user)
return render(request,'customer/show_customer.html',{'customer':customer})
show_customer.html
<html>
{% for cust in customer %}
{{cust.name}}
{{cust.contact}}
**Here I want sum of paid & sum of receive for current customer**
</html>
解决方案
您可以使用 django 模型@property
装饰器。
您的客户模型
class Customer(models.Model):
name = models.CharField(max_length=30,unique=True)
contact = models.CharField(max_length=10)
@property
def received_amount(self):
return self.account.all().aggregate(Sum('received'))['received__sum']
@property
def paid_amount(self):
return self.account.all().aggregate(Sum('paid'))['paid__sum']
然后你可以在你的模板中访问它
<html>
{% for cust in customer %}
{{cust.name}}
{{cust.contact}}
{{ cust.received_amount }}
{{ cust.paid_amount }}
</html>
希望这会帮助你!
推荐阅读
- ssis - XML SSIS 配置文件
- excel - 当值在定义的日期内超过给定值时查找日期日期的公式
- database - 找不到导入的项目
- c# - 删除父项时删除子项
- html - 中心绝对值 UL's LI
- java - 在 WebView 中选择元素并获取详细信息
- java - 如何用 JPanel 填充 JFrame 窗口?
- firebase - Firebase 动态链接在 gmail 中被标记为可疑
- python - 如何从未在其中定义“def main”的 Python 文件中导入 main 函数?
- swift - UIPageViewControllerDelegate:'NSInternalInconsistencyException',原因:'无效参数不满足:[views count] == 3'