如何在django中使用模板过滤器访问反向外键单个字段的和?

如何在django中使用模板过滤器访问反向外键单个字段的和?,django,Django,假设我有两个模型:客户和客户 型号 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

假设我有两个模型:客户和客户

型号

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>

{客户%中的客户为%1}
{{cust.name}
{{cust.contact}
**在这里,我想为当前客户支付的金额和收到的金额**

您可以使用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>

{客户%中的客户为%1}
{{cust.name}
{{cust.contact}
{{客户已收到金额}
{{客户已付金额}

希望这能帮到你

我的问题是关于Django的。你应该使用你创建的相关名称(最好将其重命名为accounts),在模板中你尝试了这个,但它给了我一个错误:received_amount()缺少1个必需的位置参数:“obj”这是一个很好的答案,但不需要
@property
装饰器。decorator允许Python代码调用该方法,而无需使用通常的尾随括号(例如,
cust.paid\u amount()
),但模板语言不使用parens来表示方法调用,因此decorator对于该用例是非常有用的。是的,您是对的,我们在模板中不使用括号。这是工作没有财产装饰…谢谢。