首页 > 解决方案 > 在 django 中加入两个查询集但保持它们的顺序?

问题描述

class WordListView(ListView):
    model = Word
    template_name = 'vocab/home.html'
    context_object_name = 'words'
    current_user = self.request.user
    if current_user.is_authenticated:
        all_words = Word.objects.filter(user=current_user)
        studying_words = all_words.filter(currently_studying=True).order_by('?')
        other_words = all_words.filter(currently_studying=False).order_by('?')
        return studying_words|other_words
    else:
        return Word.objects.none()

我尝试使用 .join() 和 | 和联合,但它们都不起作用,因为它们要么已经过时,要么不保持随机顺序。有没有办法做到这一点?

标签: pythondjango

解决方案


您可以currently_studying先按降序排列字段,然后按随机顺序排列。

from django.contrib.auth.mixins import LoginRequiredMixin

class WordListView(LoginRequiredMixin, ListView):
    model = Word
    template_name = 'vocab/home.html'
    context_object_name = 'words'

    def get_queryset(self, *args, **kwargs):
        return super().get_queryset(*args, **kwargs).filter(
            user=self.request.user
        ).order_by('-currently_studying', '?')

由于QuerySet依赖于另一个字段,因此您需要覆盖.get_queryset(…)方法 [Django-doc]


注意:您可以使用LoginRequiredMixinmixin [Django-doc]将视图限制为对经过身份验证的用户的基于类的视图 。


推荐阅读