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

问题描述 投票:0回答:1

假设我有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
1个回答
0
投票

您可以使用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, obj):
        return obj.account.all().aggregate(Sum('received'))['received__sum']

    @property
    def paid_amount(self, obj):
        return obj.account.all().aggregate(Sum('paid'))['paid__sum']

然后您可以在模板中访问它

<html>
{% for cust in customer %}
    {{cust.name}}
    {{cust.contact}}
    {{ cust.received_amount }}
    {{ cust.paid_amount }}
</html>

希望这会帮到您!

© www.soinside.com 2019 - 2024. All rights reserved.