Best way to use django rest framework instead of django orm

I am using django-rest-framework for api for my webapp. Is it good to use django rest framework instead of default ORM provided by django ? I referenced this post and am still confused. Since drf-api requires the creation of classes, and I think it is better to use this code to process objects, since I can reuse the code.

urls.py

 router = routers.DefaultRouter() router.register(r'users', views.UserViewSet) 

views.py

 class UserViewSet(viewsets.ModelViewSet): """ API endpoint that allows users to be viewed or edited. """ queryset = User.objects.all() serializer_class = UserSerializer 

serializers.py

 class UserSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = User fields = ('url', 'username', 'email', 'groups') 

How can I handle objects with the crud method in views.py using the django rest framework?

+7
rest api django django-rest-framework
source share
2 answers

There are two layers here: Model and Model Serializer ; Model is the bottom layer.

  • When you need to interact with a database in a Django application, you must use Model .
  • When you need to interact with a database with a client, you can ...

    • A: create a view that works in the traditional way of rendering content on the server side and then sends a POST request from the client to the view if you want to change (i.e. django-forms ) or ...
    • B: Install a REST API that allows you to retrieve and update the contents of a database using an AJAX request. This is the purpose of the API .
  • If you have any logic that should be executed regardless of whether you are dealing with Model or Model Serializer , then it should be implemented at the lower level, that is, Model .

The reason we often use the API today, even though we do not create an external application, is because it allows us to use more interactive and faster user interfaces. The most popular front-end frameworks today (e.g. angularjs ) are built around the concept of using the API .

+1
source share

I would like to add a possible scenario to Arnar Ingwason's excellent answer.

  • C: You can use the DRF view view from your view code.

      review_metas_response = ReviewMetaViewSet.as_view({ 'get': 'user_visit_list' })(request, format="json", limit=REVIEW_META_NUM) 
  • D: You can use the DRF serializer from your view code.

      review_meta = ReviewMeta.objects.get(id=review_meta_id) serializer = ReviewMetaSerializer(review_meta, context=context) 

I try to make the model thick (many methods) and make the DRF serializer & viewset thick and make the view thin.

+1
source share

All Articles