2010-09-20 93 views
3

我已经在Django以下模板,我想最后2列的总计为每个我的文档中总结对象Django模板

{% for documento in documentos %} 
    {% for cuenta in documento.cuentasxdocumento_set.all %} 
     <tr {% cycle 'class="gray"' '' %} > 
      {% if forloop.first %} 
        <td>{{ documento.fecha_creacion.date }}</td> 
        <td>{{ cuenta.cuenta.nombre }}</td> 
        <td> 
         {% if cuenta.monto >= 0 %} 
          {{ cuenta.monto}} 
         {% endif %} 
        </td> 
        <td> 
         {% if cuenta.monto <= 0 %} 
          {{ cuenta.monto }} 
         {% endif %} 
        </td> 
      {% else %} 

        <td colspan="4"></td> 
        <td>{{ cuenta.cuenta.codigo }}</td> 
        <td>{{ cuenta.cuenta.nombre }}</td> 
        <td> 
         {% if cuenta.monto <= 0 %} 
          {{ cuenta.monto }} 
         {% endif %} 
        </td> 
        <td> 
         {% if cuenta.monto >= 0 %} 
          {{ cuenta.monto }} 
         {% endif %} 
        </td> 

      {% endif %} 
     </tr> 
    {% endfor %} 
    <tr> 
     <td colspan="1"></td> 
     <td>Document Total</td> 
     <td></td> 
     <td></td> 
    </tr> 
{% endfor %} 

这是使用以下机型,全部完成这简化对这个问题的目的

class Documento(models.Model): 
    numero_impreso = models.CharField(max_length=50) 
    fecha_creacion = models.DateTimeField(auto_now_add = True) 


    cuentas = models.ManyToManyField('CuentaContable', through = 'CuentasXDocumento', null = True) 

    def __unicode__(self): 
     return self.tipo.nombre + ": " + self.numero_impreso 

class CuentasXDocumento(models.Model): 
    cuenta = models.ForeignKey('CuentaContable') 
    documento = models.ForeignKey('Documento') 

    monto = models.DecimalField(max_digits= 14, decimal_places = 6) 
    linea = models.IntegerField() 

class CuentaContable(models.Model): 
    codigo = models.CharField(max_length=50) 
    nombre = models.CharField(max_length=100)  
    def __unicode__(self): 
     return self.nombre 

最后我的英语不好:)

回答

2

我与Django的经验很抱歉,我会说,这些事在模板中不容易完成。我试图在视图中而不是模板中进行计算。

我的建议是计算在视图中需要的两个总和而不是模板。

众生说,使用custom filters and tags可以在模板中做一些工作。使用过滤器可能如下所示:

<td>{% documento.cuentasxdocumento_set.all | sum_monto:"pos" %}</td> 
<td>{% documento.cuentasxdocumento_set.all | sum_monto:"neg" %}</td> 

过滤器带有两个参数,即传递给过滤器的值和可用于控制其行为的参数。您可以使用最后一个参数来告知sum_monto将正值或负值相加。

这是一个快速的未经检验的过滤器实现了我的头顶部:

from django import template 

register = template.Library() 

@register.filter 
def sum_monto(cuentas, op): 
    if op == "pos": 
     return sum(c.monto for c in cuentas if c.monto > 0) 
    else 
     return sum(c.monto for c in cuentas if c.monto < 0) 
+1

谢谢,我不会有过滤器的想,我需要做的是在模板,因为它是一个任意号码Documentos – armonge 2010-09-20 18:07:46

+0

任意数量的文档如何阻止您计算视图中的总和? – Arlaharen 2010-09-20 19:47:19

+0

我不知道...也许是因为我是django的noob和更多用于PHP的方式的事情, – armonge 2010-09-20 20:21:04