Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Query selector sort

Inbox = Messages.objects.filter(Q(sender=request.user) | Q(receiver=request.user))
context['Inbox'] = Inbox

Currently I am using this to grab all messages for the currently logged in user.

I want to sort it by time and read status. So that the lastest unread message shows up first.

models.py

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

class Messages(models.Model):
    sender = models.ForeignKey(Profile,related_name='sender',on_delete=models.CASCADE)
    receiver = models.ForeignKey(Profile,related_name='receiver',on_delete=models.CASCADE)
    subject = models.CharField(default='',max_length=100)
    text = models.CharField(default='',max_length=4096)
    time = models.DateTimeField(auto_now_add=True)
    read = models.BooleanField(default=False)

    def __str__(self):
        return '{} to {} :{}'.format(self.sender,self.receiver,self.text)

>Solution :

This can be achieved using the Model.objects.order_by(). In your case, this will look like this:

Inbox = Messages.objects.filter(Q(sender=request.user) | Q(receiver=request.user)).order_by("-time", "read")

Or "-read", depending if you want them to be sorted ascending/descending.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading