title: Optimize Django Query in loop with branch
body: <p>I'm working on a Django project, on a certain view I want to retrieve all the payment orders for all clients, and its payment.</p>
  
  <p>The main query is this one:</p>
  
  <pre><code>orders = PaymentOrder.objects.filter(
      created_date__gte=init_date, created_date__lte=end_date
  ).values(
      'invoice_sat__comp_folio', 'created_date', 'client__name',
      'client__last_name', 'total', 'status', 'pk', 'client__pk'
  ).order_by('-created_date')
  </code></pre>
  
  <p>Also, I want the paid amount for each Order, and I'm doing this:</p>
  
  <pre><code>for order in orders:
      order_payments = Payment.objects.filter(
          order__pk=order['pk']
      ).values('amount').aggregate(total=Sum('amount'))
      if order_payments['total'] is not None:
          to_pay = order['total'] - order_payments['total']
      else:
          to_pay = order['total']
      order.update(to_pay=to_pay)
  </code></pre>
  
  <p>The problem here is, the template takes a very long time to load, I have something like 15,000 results. Is there any way to optimize the query, or, to update the extra info (amount to pay) of the orders.</p>
  
  <p>Thanks a lot!</p>
  
  <p><strong>MODELS UPDATE:</strong></p>
  
  <pre><code>class PaymentOrder(models.Model):
      STATUS = (
          (0, "Por Pagar"),
          (1, "Pagado"),
      )
      client = models.ForeignKey(Client, verbose_name='Cliente')
      invoice_sat = models.ForeignKey(InvoiceSAT, blank=True, null=True)
      invoice_period = models.DateField(verbose_name="Periodo de     Facturación")
      created_date = models.DateTimeField(verbose_name='Fecha de Creacion',
                                      default=datetime.datetime.now(),
                                      db_index=True)
      cancelled_date = models.DateField(verbose_name='Fecha de Cancelacion',
                                    default=None, null=True, blank=True)
      due_date = models.DateField(verbose_name="Fecha de Vencimiento")
      status = models.IntegerField(max_length=1, choices=STATUS, default=0)
      subtotal = models.DecimalField(max_digits=10, decimal_places=2,
                                 verbose_name='Subtotal', default=0)
      total = models.DecimalField(max_digits=10, decimal_places=2,
                              verbose_name="Cantidad", default=0)
  
  class Payment(models.Model):
      order = models.ForeignKey(PaymentOrder, verbose_name='Orden de Pago')
      payment_date = models.DateField(verbose_name="Fecha de Pago")
      amount = models.DecimalField(max_digits=10, decimal_places=2,
                               verbose_name="Cantidad a pagar")
  </code></pre>