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()と|を使用してみました とユニオンですが、古くなっているか、ランダムな順序を維持していないため、いずれも機能しません。これを行う方法はありますか?
最初に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(…)
法[ジャンゴ-docの]。
注:
LoginRequiredMixin
ミックスイン[Django-doc]を使用して、ビューをクラスベースのビューに制限し、認証されたユーザーに限定することができます。
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加