'DjangoORM/Postgres: Get latest row based on distinct values of certain column when ordered by date

I have a Django model called Comment (database is Postgres) which I populate with responses from an external API.

class Poster(models.Model):
    username = models.TextField()

class Comment(models.Model):
    created_dt = models.DateTimeField()
    body = models.TextField()
    poster = models.ForeignKey('Poster', on_delete=models.PROTECT, related_name = 'comments'
    client_version = models.CharField(max_length=30)
    

Each comment object in the API response contains a client_version which is the version of the android client used by the poster to submit said comment.

I wish to write a query which tells me which client_version each poster submitted their most recent comment with, to identify which posters should be instructed to upgrade their client.

In this example scenario, let's assume that once a poster has upgraded their android client to a new version they can't go back to an earlier version; so the client_version from their latest comment is indicative of the version that poster is currently using.

To do this for a single poster is easy:

def get_latest_version(poster):

    return Comment.objects.filter(
        poster__username=poster
        ).order_by('-created_dt'
        ).values('poster__username', 'client_version').first()


>>> get_latest_version('kevin')
{'poster__username': 'kevin', 'client_version': 'v4.20.0'}

Obviously running this code for every individual poster is inefficient.

How can I use the Django ORM to perform a single postgres query, which returns something like:

[{'poster__username': 'kevin', 'client_version': 'v4.20.0'},
 {'poster__username': 'perry', 'client_version': 'v4.21.0'},
 {'poster__username': 'paul', 'client_version': 'v4.20.0'},
]


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source