cutteeth
cutteeth

Reputation: 2213

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 in place of default ORM provided by django? I have refered to this post and still confused. As drf-api requires classes to be created and I think its better to use that code for handling objects since I can reuse 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 the crud way in views.py using django rest framework?

Upvotes: 4

Views: 1822

Answers (2)

eugene
eugene

Reputation: 41685

I'd like to add a possible scenario to Arnar Yngvason's excellent answer.

  • C: You can use DRF's viewset 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 DRF's serializer from your view code.

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

I tend to make model thick (many methods) and make DRF serializer & viewset thick and make views thin.

Upvotes: 1

demux
demux

Reputation: 4654

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

  • When you need to interact with the database within your Django Application you should use the Model.
  • When you need to interact with the database from the client, you can either...

    • A: create a view which, works in the traditional way of rendering the content on the server side and then send back a POST request from the client to the view, if you want to edit (i.e. django-forms) , or...
    • B: Setup a REST API that lets you fetch and update your database content via AJAX request. This is the purpose of an API.
  • If you have any logic that has to run regardless of whether you're dealing with the Model or the Model Serializer, then it should be implemented on the bottom layer, i.e. the Model.

The reason we often today use an API even though we're not building an external application is that it allows for more interactive and faster user interfaces. Most popular front-end frameworks today, (for example angularjs), are built around the concept of using an API.

Upvotes: 3

Related Questions