[DRF] 인스타그램 클론코딩하기-Viewset&Filtering

Cherry·2022년 1월 29일
0
post-thumbnail

viewset으로 리팩토링하기

class PostViewSet(ModelViewSet):
    serializer_class = PostSerializer
    queryset = Post.objects.all()
    filter_backends = [DjangoFilterBackend] 
    filter_class = PostFilter


class ProfileViewSet(ModelViewSet):
    serializer_class = ProfileSerializer
    queryset = Profile.objects.all()
    filter_backends = [DjangoFilterBackend]
    filter_class = ProfileFilter

먼저 뷰를 viewset으로 리팩토링 해줬다. CRUD를 직접 정의안해줘도 알아서 장고에서 구현해줘서
너무나 편리하고 신기했다. 전에는 코드가 꽤 길었는데 viewset으로 사용하니까 두줄만 써도 POST, GET, PUT, DELETE
이 다 작동되었다.

Filtering

class PostFilter(FilterSet):
    title = filters.CharFilter(field_name='title', lookup_expr="icontains")#해당 문자열을 포함하는 queryset
    content_null = filters.BooleanFilter(field_name='content', method='is_content_null')#true 시에 content가 null인것만 출력

    class Meta:
        model = Post
        fields = ['title', 'content']

    def is_content_null(self, queryset, content, value):
        if value:
            return queryset.filter(content__isnull=True)
        else:
            return queryset.filter(content__isnull=False)


class ProfileFilter(FilterSet):
    nickname = filters.CharFilter(field_name='nickname')

    class Meta:
        model = Profile
        fields = ['nickname']

처음에는 꼭 전체 단어를 검색해야지 해당 queryset을 가져올 수 있었는데
lookup_expr="icontains"를 포함했더니 해당 단어의 특정 문자열만 검색해도 queryset을 반환할 수 있었다.

lookup_expr는 필터링 할 때 필드를 가져온다. 장고에서 __구문 은 조회된 결과의 조건에 대한 변환을 지원 한다.
기본값은 'iexact'이고 이외에도 'isnull', 'in'도 있다.

Postman 결과

[GET] http://127.0.0.1:8000/api/profiles

[
    {
        "user": 1,
        "nickname": "cherry",
        "introduction": "heyyyyyyy"
    },
    {
        "user": 2,
        "nickname": "choco",
        "introduction": "멍멍"
    },
    {
        "user": 3,
        "nickname": "backend",
        "introduction": "후후"
    }
]

[GET] http://127.0.0.1:8000/api/profiles/?nickname=chaeri

[
    {
        "user": 1,
        "nickname": "cherry",
        "introduction": "heyyyyyyy"
    }
]

[GET] http://127.0.0.1:8000/api/posts/?title=choco

[
    {
        "author": 3,
        "title": "chocolate",
        "content": "",
        "author_nickname": "choco",
        "created_at": "2021-11-19T01:24:00.405420+09:00",
        "updated_at": "2021-11-19T01:43:41.202731+09:00",
        "post_like": [],
        "post_comment": []
    },
    {
        "author": 3,
        "title": "chococo",
        "content": null,
        "author_nickname": "choco",
        "created_at": "2021-11-19T01:26:15.250002+09:00",
        "updated_at": "2021-11-19T01:26:15.250002+09:00",
        "post_like": [],
        "post_comment": []
    }
]

[GET] http://127.0.0.1:8000/api/posts/?content_null=true

[
    {
        "author": 3,
        "title": "chococo",
        "content": null,
        "author_nickname": "choco",
        "created_at": "2021-11-19T01:26:15.250002+09:00",
        "updated_at": "2021-11-19T01:26:15.250002+09:00",
        "post_like": [],
        "post_comment": []
    },
    {
        "author": 1,
        "title": "hungry",
        "content": null,
        "author_nickname": "cherry",
        "created_at": "2021-11-19T01:52:46.304923+09:00",
        "updated_at": "2021-11-19T01:52:46.304923+09:00",
        "post_like": [],
        "post_comment": []
    }
]

[GET] http://127.0.0.1:8000/api/posts/?content_null=true&title=choco

[
    {
        "author": 3,
        "title": "chococo",
        "content": null,
        "author_nickname": "choco",
        "created_at": "2021-11-19T01:26:15.250002+09:00",
        "updated_at": "2021-11-19T01:26:15.250002+09:00",
        "post_like": [],
        "post_comment": []
    }
]

0개의 댓글