TIL[88].SQL에서 페이지네이션 &필터

jake.log·2020년 11월 8일
0

웹페이지에서 상품 목록, 회원 목록 등을 볼때 가장 중요한 기능 중 하나가, 페이지네이션과 필터 기능이다.

기업협업 프로젝트를 하기 전 1,2차 프로젝트에서는 Django에서 가격순,최신순 필터 기능을 작성한 바 있다.

당시 필터 기능은 order_by 로 정렬만 하면 되는 기능이었는데 이번엔 검색을 통한 필터를 SQL로 구현해야했다.

필터와 페이지네이션 기능은 flask의 controller에서 받은 인자를 model로 가져와 model에서 처리를 해준다. 프론트에서 보내지 않은 인자의 경우는 필터를 할 필요가 없고, 값을 보내게 될 경우 그 값만 가져와 표출해준다.

해당 코드는 다음과 같이 이루어진다.

 def get_seller_list(self,seller_list,db_connection):
        """    
        with db_connection.cursor(pymysql.cursors.DictCursor) as cursor:
            query = """
            SELECT 
                sellers.id,
                a.id as account_id,
                a.identification,
                english_name,
                korean_name,
                m.name as manager_name,
                s.name as status_name,
                m.contact,
                m.email,
                at.name as attiribute,
                DATE_FORMAT(sellers.created_at,'%%Y-%%m-%%d %%H:%%m:%%s')AS created_at,
                s.id as status_id
            FROM 
                sellers 
            JOIN 
             .
             .(중략)
             .
            """
           
            #셀러 필터 기능, seller_list에 검색 키워드가 있는지 확인 후에 쿼리 추가.
            if seller_list['id']:
                query +="""
                sellers.id = %(id)s
                """
            print(seller_list)
            if seller_list['identification']:
                query +="""
                AND a.identification = %(identification)s
                """ 
            
           .
           .
           (중략)
           .
           .
            
            query+= """
            ORDER BY 
                sellers.id 
            DESC 
            LIMIT 
                %(limit)s
            OFFSET
                %(offset)s
            """
             
            cursor.execute(query, seller_list)
            total_seller_number = cursor.fetchall() 
            return total_seller_number 

앞서 말할 것처럼 셀러 필터 기능은 받아오는 인자들의 변수인 seller_list에 id라는 검색 키워드가 있는지 확인을 해준 후에 있으면 쿼리를 추가해 그 해당 데이터만 select 해서 표출해준다.

         if seller_list['id']:
             query +="""
             sellers.id = %(id)s

페이지네이션에 경우 프론트에서 보내주는 limit값과 offset 값을 받아 요청하는 범위의 데이터를 보내준다.

 query+= """
            ORDER BY 
                sellers.id 
            DESC 
            LIMIT 
                %(limit)s
            OFFSET
                %(offset)s
            """
profile
꾸준히!

0개의 댓글