Django or Django Rest Framework

后端 未结 7 838
北荒
北荒 2021-01-30 06:28

I have made a certain app in Django, and I know that Django Rest Framework is used for building APIs. However, when I started to read about Django Rest Framework on their websit

7条回答
  •  难免孤独
    2021-01-30 06:52

    Django Rest Framework makes it easy to use your Django Server as an REST API.

    REST stands for "representational state transfer" and API stands for application programming interface.

    You can build a restful api using regular Django, but it will be very tidious. DRF makes everything easy. For comparison, here is simple GET-view using just regular Django, and one using Django Rest Framework:

    Regular:

    from django.core.serializers import serialize
    from django.http import HttpResponse
    
    
    class SerializedListView(View):
        def get(self, request, *args, **kwargs):
            qs = MyObj.objects.all()
            json_data = serialize("json", qs, fields=('my_field', 'my_other_field'))
            return HttpResponse(json_data, content_type='application/json')
    

    And with DRF this becomes:

    from rest_framework import generics
    
    
    class MyObjListCreateAPIView(generics.ListCreateAPIView):
        permission_classes = [permissions.IsAuthenticatedOrReadOnly]
        serializer_class = MyObjSerializer
    

    Note that with DRF you easily have list and create views as well as authentication.

提交回复
热议问题