I have the following models in Django (simplified for brevity):
class DistinctWord(models.Model):
...
class Word(models.Model):
distinct_word = models.F
You can do this using the Subquery API:
from django.db.models.expressions import Subquery, OuterRef
first_word = Word.objects.filter(
distinct_word=OuterRef('distinct_word')
).order_by('pk').values('pk')[:1]
UserWord.objects.filter(
# whatever filters...
).annotate(
first_word=Subquery(first_word)
)
This will result in SQL that looks something like:
SELECT user_word.*,
(SELECT word.id
FROM word
WHERE word.distinct_word_id = user_word.distinct_word_id
) AS first_word
FROM user_word
WHERE ...
This will probably not perform as well as a JOIN with a DISTINCT ON in postgres, and may not perform as well as a JOIN with a GROUP BY, as it will need to execute the subquery for each row.