tunEmvegnomb / gomunity

내일배움캠프 프로젝트 거뮤니티
0 stars 4 forks source link

검색기능 #108

Open kti0940 opened 2 years ago

kimheejeong3808 commented 2 years ago

DRF Search APIView


목차

Generic views

개발 레퍼런스

DRF를 활용하여 검색 기능을 활용하자!

사용법

🔥 generics.ListAPIView

from rest_framework import generics, filters

📌 queryset

📌 serializer_class

📌 filter_backends

📌 search_fields

☝ URL 바인딩

😁 시리얼라이저

👨‍💻 코드

시리얼라이저

class QuestionSerializer(serializers.ModelSerializer):
    answer = AnswerSerializer(many=True, source="qnaanswer_set", read_only=True)
    user = serializers.SerializerMethodField()

        #기존 이미지 시리얼라이저를 침해하지 않기 위해 새로운 변수명 설정
    image_path = serializers.SerializerMethodField()

    def get_user(self, obj):
        return obj.user.username

        # 메소드 필드를 활용 get
    def get_image_path(self, obj):
        print(obj.image)
        return "/media/" + str(obj.image)

    class Meta:
        model = QnAQuestionModel
        fields = "__all__"

제너릭 뷰

from rest_framework import status, generics
from django_filters.rest_framework import DjangoFilterBackend
from rest_framework import filters

class QuestionSearchView(generics.ListAPIView):
        queryset = QnAQuestionModel.objects.all().order_by('-created_at')
        serializer_class = QuestionSerializer
        filter_backends = [filters.SearchFilter]
        search_fields = ['user__username', 'title', 'content', 'hashtag']

프론트엔드 Fetch API

//검색기능
async function searchFilter() {
    let inputvalue = document.getElementById("search_input").value;

    const response = await fetch(`${backend_base_url}/qna/list/search?search=${inputvalue}`, {
        method: 'GET',
    })
    const response_json = await response.json();
    const searchedQuestions = response_json;

    // const searchedQuestions = await getSearch();
    console.log(searchedQuestions);
    const element = document.querySelectorAll(".col");
    element.forEach((card)=>card.remove());

    const div_cards = document.getElementsByClassName("cards")[0];

    //검색 값
    searchedQuestions.forEach((question) => {
        const div_count = document.createElement("div");
        div_count.setAttribute("class","count-list");
        div_count.innerText = " 좋아요💕"+ question.like.length+"   댓글💬 "+ question.answer.length;
        div_card_body.appendChild(div_count);
        if(question.image_path == "/media/"){
            imagecard.style.backgroundImage = `url('https://s3.ap-northeast-2.amazonaws.com/gomunity.shop/media/gomunitydefault.jpg')`;
        } else {
            imagecard.setAttribute("style", "backgroundImage");
            imagecard.style.backgroundImage = `url('https://s3.ap-northeast-2.amazonaws.com/gomunity.shop${question.image_path}')`;
        }
    })
    }