2

I want to execute this MySQL query in Django:

SELECT Descripcion,count(*)
FROM votaciones.Tarjeton 
WHERE Voto_idVoto=1 
GROUP BY Descripcion;

Expected result from MySQL:

'', '1'

'Camilo Gomez Ortega', '3'

'JUan Jose Marquez', '3'

'Pedro Pablo de la Mar', '15'

'Sandra Mejia Gutierez', '4'

My model is:

class Tarjeton(models.Model):
idtarjeton = models.AutoField(db_column='idTarjeton', primary_key=True)  # Field name made lowercase.
descripcion = models.CharField(db_column='Descripcion', max_length=45)  # Field name made lowercase.
cadidatos_idcadidatos = models.ForeignKey(Cadidatos, models.DO_NOTHING, db_column='Cadidatos_idCadidatos')  # Field name made lowercase.
voto_candidato = models.ForeignKey('Voto', models.DO_NOTHING, db_column='Voto_idVoto')  # Field name made lowercase.

class Meta:
    managed = False
    db_table = 'Tarjeton'
Jedi
  • 3,088
  • 2
  • 28
  • 47
  • You should look at the examples in [Django aggregation](https://docs.djangoproject.com/en/1.11/topics/db/aggregation/). Possible duplicate of https://stackoverflow.com/a/629691/6382901 – Jedi Jun 03 '17 at 01:10

1 Answers1

2

Try this way:

from django.db.models import Count
Tarjeton.objects.filter(voto_candidato=1).values('descripcion').annotate(Count('descripcion')).order_by()
Tiny.D
  • 6,466
  • 2
  • 15
  • 20