[Fixed]-Group By Django ORM

1👍

Technically, you do a GROUP BY with .group_by(), but it’s not exactly what you are looking for.

You can achieve your goal with the ORM using a prefetch_related.

The Prefetch objects allow you to do all kind of lookup using the ORM.

In your case :

User.objects.prefetch_related(
    Prefetch(
        'photos',
        queryset=Photo.objects.last(),
    )
)

Where ‘photos’ is you related_name or ‘photo_set’ by default. Also, the .last() method can be replaced by the .order_by() of your choice.

Take note that it will differs from your SQL example in the fact that the prefetch will do an additional query instead of a JOIN.

Leave a comment