I'm trying to get all the conversations ordered by it last message, but when I use the order_by
clausule, the conversations are repeated.
Query without order_by:
conversaciones = Conversacion.objects.filter(usuarios=request.user)
Result (Grouped by Conversations but not ordered by the most recent last message first):
Query with order_by:
conversaciones = Conversacion.objects.filter(usuarios=request.user).order_by('-mensaje__fechaEnvio')
Result:
My models.py:
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')
cuerpo = models.TextField(validators=[MaxLengthValidator(750)])
leido = models.BooleanField(default=False)
fechaEnvio = models.DateTimeField(auto_now_add=True)
conversacion = models.ForeignKey('Conversacion', on_delete=models.CASCADE)
class Meta:
ordering = ['-fechaEnvio']
def __str__(self):
return str(self.remitente) + ' -> ' + str(self.destinatario)
class Conversacion(models.Model):
usuarios = models.ManyToManyField('Usuario', related_name='usuarios')
agresion = models.ForeignKey('Agresion', on_delete=models.CASCADE)
@property
def ultimoMensaje(self):
return self.mensaje_set.latest('fechaEnvio')
I found a solution:
conversaciones = Conversacion.objects.filter(usuarios=request.user).annotate(max_fecha=Max('mensaje__fechaEnvio')).order_by('-max_fecha')
I'm using MySQL so I can't use distinct with params.
As @jota suggested, I can add something in your model Mesanje. Make ordering a tuple and don't forget to add a comma and don't forget to make migrations again.
class Mesanje(models.Model):
........
class Meta:
ordering = ('-fechaEnvio',)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.