Django prefetch_related with limit

后端 未结 3 833
情歌与酒
情歌与酒 2020-12-05 09:40

Is there a way to tell prefetch_related to only fetch a limited set of related objects? Lets say I am fetching a list of users and I know I want to fetch their

3条回答
  •  佛祖请我去吃肉
    2020-12-05 10:22

    I think there is a workaround now to in django new version as we have OuterRef and Subquery.

    from django.db.models import OuterRef, Subquery, Prefetch
    
    subqry = Subquery(Comment.objects \
        .filter(user_id=OuterRef('user_id')) \
        .values_list('id', flat=True)[:5])
    
    User.objects.prefetch_related(
        Prefetch('comments', queryset=Comment.objects.filter(id__in=subqry)))
    

提交回复
热议问题