ORM: emulating SELECT DISTINCT ON in non-PostgreSQL DBs (or just sqlite)

I was using the PostgreSQL only feature of distinct("col_1", "col_2") to weed out duplicate rows while also returning a few other non-distinct columns, say col_3 and col_4 in a QuerySet. When it came time to test this code is when I learned that this feature was not available in sqlite, which is the DB being used for testing currently.

I rewrote the query to use a plain .distinct() and while the results are different, they are acceptable and possibly even better in my point of view so that isn’t my real issue.

Can anyone share a general way this could be done in Django? If a more concrete example is needed, I can whip one up (hopefully using the classic pizza restaurants).

I spent some time trying to figure out ways to duplicate this feature using other bits of the QuerySet API including subqueries with Exists() because I had see #32682 (Deleting objects after searching related many to many field crashes the admin page) – Django and then also with a FilteredRelation because I had seen this SELECT DISTINCT ON in PostgreSQL | Geeky Tidbits . I think the best I could do was to duplicate the results of using a plain .distinct() so far.

If I continue, I’ll probably look at using .extra() but that and RawSQL feels like cheating.

Thanks.