Group by limit 1 in django

前端 未结 3 1796
名媛妹妹
名媛妹妹 2021-01-27 10:54

I have the following models in Django (simplified for brevity):

class DistinctWord(models.Model):
    ...

class Word(models.Model):
    distinct_word = models.F         


        
3条回答
  •  闹比i
    闹比i (楼主)
    2021-01-27 11:46

    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.

提交回复
热议问题