Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
534 views
in Technique[技术] by (71.8m points)

generics vs viewset in django rest framework, how to prefer which one to use?

How to prefer which one of generics and viewset to use? in other words when should I use generics and when should i use viewset for building api. I know that it does the same thing, but viewset has routers, so in what situation generics is better then viewset?

question from:https://stackoverflow.com/questions/49482453/generics-vs-viewset-in-django-rest-framework-how-to-prefer-which-one-to-use

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

They are different, let's see.

DRF has two main systems for handling views:

  1. APIView: This provides methods handler for http verbs: get, post, put, patch, and delete.
  2. ViewSet: This is an abstraction over APIView, which provides actions as methods:
    • list: read only, returns multiple resources (http verb: get). Returns a list of dicts.
    • retrieve: read only, single resource (http verb: get, but will expect an id in the url). Returns a single dict.
    • create: creates a new resource (http verb: post)
    • update/partial_update: edits a resource (http verbs: put/patch)
    • destroy: removes a resource (http verb: delete)

Both can be used with normal django urls.

Because of the conventions established with the actions, the ViewSet has also the ability to be mapped into a router, which is really helpful.

Now, both of this Views, have shortcuts, these shortcuts give you a simple implementation ready to be used.

GenericAPIView: for APIView, this gives you shortcuts that map closely to your database models. Adds commonly required behavior for standard list and detail views. Gives you some attributes like, the serializer_class, also gives pagination_class, filter_backend, etc

GenericViewSet: There are many GenericViewSet, the most common being ModelViewSet. They inherit from GenericAPIView and have a full implementation of all of the actions: list, retrieve, destroy, updated, etc. Of course, you can also pick some of them, read the docs.

So, to answer your question: DRY, if you are doing something really simple, with a ModelViewSet should be enough, even redefining and calling super also is enough. For more complex cases, you can go for lower level classes.

Hope to have helped you!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...