[django] 다음글 or 이전글로 넘어가기 구현

star_is_mine·2022년 12월 15일
0

페이지 내에서 빠져나가지 않고 <다음글> 버튼을 눌러 다음 카드로 바로 넘어갈 수 있게 하고 싶었다.

처음엔 단순히 pk+1, pk-1이런식으로 페이지를 넘길수 있게하면 되겠다고 생각했지만 도중에 삭제된 글이 있다면 중간에 pk가 연속적이지 않을 수 있다.

이를 아래와 같이 해결했다.

def run_level_exam(request, level, index):
    if request.method == 'GET':
        exam_word = Word.objects.filter(word_level=level).get(pk=index)        
        next_exam_word = Word.objects.filter(word_level=level).filter(pk__gt=index).order_by('pk').first()
        prev_exam_word = Word.objects.filter(word_level=level).filter(pk__lt=index).order_by('pk').last()
        
        context = {
            "exam_word" : exam_word,
            "today_date" : today_date,
            "next_exam_word" : next_exam_word,
            "prev_exam_word" : prev_exam_word
        }
        return render(request, '../templates/quiz/run_level_exam.html', context)

위 코드는 단어시험용 코드다.
한 페이지에 단 하나의 단어시험을 본다. exam_word
각 단어는 레벨속성을 가지고 있다.(word_level)

따라서 특정 레벨에 맞는 단어를 추출한다.
exam_word = Word.objects.filter(word_level=level).get(pk=index)

그리고 그 단어의 바로 다음에 존재하는 단어를 추출한다.
next_exam_word = Word.objects.filter(word_level=level).filter(pk__gt=index).order_by('pk').first()

그 단어의 바로 직전에 존재하는 단어도 추출한다.
prev_exam_word = Word.objects.filter(word_level=level).filter(pk__lt=index).order_by('pk').last()

이후 하던데로... context 변수에 담아서 전달~ DONE.

처음에 filter(pkgt=index) 으로 추출한 이후 이를 다시 .order_by('pk') 정렬해주면 현재 pk에 해당하는 오브젝트를 기준으로 이후에 존재하는 오브젝트 들을 pk 순서대로 정렬해준다는 것을 생각해내지 못했다. 사실 애초부터 ㅋㅋ filter(pkgt=... 자체가 익숙하지 않았던 것이 솔직한 마음이다. ㅋㅋㅋ 아무튼 이제 알았으니 됐지뭐 ㅋㅋ

오늘도 해결~~ ^^

profile
i have a dream and I will make my dreams come true.

0개의 댓글