Programming/Django

[DRF] get_queryset에서 벗어나기(get 사용)

stein 2021. 10. 15. 11:56

drf에서 api를 구현할 때, 필자는 get_queryset을 메인으로 하여 api를 구성하였다.

get_queryset을 사용하는건 아래의 docs를 참고하고 진행하였다.

https://www.django-rest-framework.org/#quickstart

 

Home - Django REST framework

 

www.django-rest-framework.org

https://www.django-rest-framework.org/api-guide/filtering/

 

Filtering - Django REST framework

 

www.django-rest-framework.org

 

다만 이렇게 get_queryset만 사용하면 결론적으로 [sql로 할 수 있는것 + serializer의 보조] 만을 사용하는 것이고, 개발자가 직접적으로 데이터를 생성한다든지, 조작하는 것이 불가능 하다고 느껴졌다. 그래서 이 때 사용하는게 get함수이다.

 

https://www.django-rest-framework.org/api-guide/views/

 

Views - Django REST framework

 

www.django-rest-framework.org

get요청이 들어왔을 때 실행되는 함수고, 아래와 같은 형태로 사용할 수 있다.

from rest_framework.response import Response

class ListUsers(APIView):
    authentication_classes = [authentication.TokenAuthentication]
    permission_classes = [permissions.IsAdminUser]

    def get(self, request, format=None):
        """
        Return a list of all users.
        """
        usernames = [user.username for user in User.objects.all()]
        return Response(usernames)

이 때는 serializer가 들어갈 수도있고, 위의 예제처럼 안들어 갈 수도 있다. 정의를 보자

Serializers allow complex data such as querysets and model instances to be converted to native Python datatypes that can then be easily rendered into JSON, XML or other content types.

querysets과 model instance를 python datatype으로 변환해준다. (아마 dict 형태)

 

따라서 querysets과 model instance를 바로 Response에 실어보내지 않는다면 serializer는 필요하지 않을 것이다. (물론 사용하려면 사용할 수 있다).