안녕하세요 추천 취소 기능을 만드려합니다.
@login_required(login_url='common:login')
def vote_question(request, question_id):
    '''
    pybo 질문 추천 등록
    '''

    #question = Question.objects.get(id=question_id)
    question = get_object_or_404(Question, pk=question_id)

    if request.user == question.author:
        messages.error(request, '본인이 작성한 글은 추천할 수 없습니다.')

    elif question.voter == request.user  :
                messages.error(request, '추천을 취소합니다.')
        print("추천을 취소합니다. : ", question.voter)

    else:
        question.voter.add(request.user)

        print("question.voter : ", question.voter)
        # print("question.__dict__ : ", question.__dict__)

    return redirect('pybo:detail', question_id=question.id)

만약 어떤 게시물에 추천을 이미 한 상태에서 추천버튼을 다시 누르면 취소가 되게 하고싶은데, 객체내부를 살펴봐도 어떤 걸로 비교해야 좋을지 모르겠습니다.. elif문에 어떤 조건을 달아줘야 할까요??

foobar 328

M 2022년 1월 25일 11:48 오전

+1 question.voter 에서 이미 들어간 사용자를 제거하시면 될것 같네요. - 박응용님, 2022년 1월 25일 2:17 오후 추천 , 대댓글
@박응용님 감사합니다. question.voter.filter(username=request.user).first()로 가져와서 했습니다. manytomany 필드 값을 가져오는게 헷갈리네요 이부분은 검색을 어떻게 해야할까요? - foobar님, 2022년 1월 25일 6:32 오후 추천 , 대댓글
목록으로