Jota
Jota

Reputation: 737

Django query does not group

I want to group the number of messages by recipient user -> {'User 1': 5};{'User 2': 7}...

My model:

class Mensaje(models.Model):
    remitente = models.ForeignKey('Usuario', on_delete=models.CASCADE, related_name='Remitente')
    destinatario = models.ForeignKey('Usuario', on_delete=models.CASCADE, related_name='Destinatario')
    mensaje = models.TextField(validators=[MaxLengthValidator(1000)]) 
    leido = models.BooleanField(default=False)
    fechaEnvio = models.DateTimeField(auto_now_add=True)

My query:

 mensajes = Mensaje.objects.filter(destinatario=request.user).values('pk', 'remitente__username').annotate(num_msg=Count('pk')).order_by('-fechaEnvio')

Result:

{'pk': 28, 'remitente__username': 'Paco', 'num_msg': 1}, {'pk': 27, 'remitente__username': 'Paco', 'num_msg': 1}, {'pk': 26, 'remitente__username': 'jota', 'num_msg': 1}, {'pk': 25, 'remitente__username': 'jota', 'num_msg': 1}...

As you can see, the query returns all the messages without group by user.

Another question: Why does not work mensajes = request.user.mensaje_set.all()?

Upvotes: 0

Views: 191

Answers (2)

JPG
JPG

Reputation: 88689

result = Mensaje.objects.values('remitente__username').annotate(num_msg=Count('pk')).order_by('remitente__username')


You did order_by as .order_by('-fechaEnvio') which has no logic in this context. ( You are trying to ordering a Table with an attribute (fechaEnvio), which is not belongs to the newly generated group_by table)

Upvotes: 1

bdoubleu
bdoubleu

Reputation: 6127

You're grouping but the message id instead of the user id. To group by the recipient's user id you would have to do .values('remitente__pk')

Upvotes: 0

Related Questions