title: How to optimize my code and the database access?
body: <p>I'm creating a sme budingeting application, where I have the necessity to manage a lot of data ( huge list of products, balance sheet table etc.). </p>
  
  <p>I want to have an efficient and optimized code, respecting the DRY principle and less querysets possible to the database. </p>
  
  <p>Ad example this code in my views.py is it efficient and optimized? </p>
  
  <pre><code>def conto_economico(request):
      # Creazione tabella materie prime, sussidiarie, di consumo e merci
      defaults = list(0 for m in range(12))
      elements = dict()
      for conto_id, year, month, totale in(Materiale.objects.values_list('conto__nome', 'data__year', 'data__month').annotate(totale=ExpressionWrapper(Sum(F('quantita') * F('prezzo')),
          output_field=FloatField())).values_list('conto__nome', 'data__year', 'data__month', 'totale').order_by("conto_id")) :
          if conto_id not in elements.keys():
              elements[conto_id]=list(defaults)
          index=month-1
          elements[conto_id][index]=totale
  
      total_elements={'Per materie prime, sussidiarie, di consumo e di merci': [sum(t) for t in zip(*elements.values())],}
  </code></pre>
  
  <p>I utilize this code for a lot of model to create my tables, but I think that are not efficient. </p>
  
  <p>This is my model: </p>
  
  <pre><code>class MaterialeManager(models.Manager):
      def get_queryset(self, *args, **kwargs):
          return super().get_queryset(*args, **kwargs).annotate(
              iva_amount=ExpressionWrapper(F('quantita')*F('prezzo')*F('iva'),output_field=FloatField())
          ).annotate(totale_netto=ExpressionWrapper(F('quantita')*F('prezzo'),output_field=FloatField()))
  
  
  class Materiale(models.Model):
      conto = models.ForeignKey(Conto, on_delete=models.CASCADE, null=True)
      tipologia = models.ForeignKey(Tipologia, on_delete=models.CASCADE, null=True)
      sottocategoria = models.ForeignKey(Sottocategoria, on_delete=models.CASCADE, null=True)
      um = models.CharField('U.M.', max_length=30, unique=False, blank=True, default="")
      quantita=models.DecimalField('Quantità',max_digits=5, decimal_places=2, default="")
      prezzo=models.DecimalField('Prezzo di acquisto', max_digits=5, decimal_places=2, default="")
      iva=models.DecimalField('I.V.A. in %', max_digits=5, decimal_places=2, default="0.22")
      data=models.DateField('Data di acquisto', default="GG/MM/YYYY")
      giorni_dilazione=models.IntegerField('Giorni dilazione pagamento', default="")
      objects=MaterialeManager()
  </code></pre>
  
  <p>I want to obtain, based on the data of registration, a monthly tables that sum all "<code>quantita</code>" amount for each single "<code>conto</code>".</p>