[Answered ]-Getting most recent instance of each category in a queryset

2👍

Unfortunately there is no way to do this reliably across all databases since the queries vary quite a bit.

With MySQL you could do something like this:

SELECT
    name,
    category,
    date
FROM
    thing
WHERE
    name LIKE '%substring%'
GROUP BY date

With PostgreSQL it would be something like this:

SELECT
    DISTINCT ON (category)
    name,
    category,
    date
FROM
    thing
WHERE
    name LIKE '%substring%'
ORDER BY date DESC

If you are using PostgreSQL, than you can use this patch to get DISTINCT ON support: http://code.djangoproject.com/ticket/6422

👤Wolph

Leave a comment