Let's create a simple hello view set class to demonstrate how you would use a
view set in practice load up the code in the atom editor and head over to the
views dot py file where we created our hello API view class in the previous
section we're going to create a new class below this called hello view set
before we do that we're going to import view sets from the rest framework so
type from rest underscore framework import view sets then below our hello
API view let's create a new class called class hello view set and we're going to
base our class on view sets dot view set which is the base view set class that
Django rest framework provides
We're going to add a doc string that says test
API view set and then we're going to add some functions to our view set so as I
explained previously the functions that you add to a view set are a little bit
different from the functions you add to an API view in an API view you add
functions for the particular HTTP methods that you want to support on your
endpoint for example HTTP POST HTTP put HTTP patch and HTTP delete for a view
set you add functions that represent actions that you would perform on a
typical API so the action that we're going to add is the list so a list is
typically a HTTP GET to the root of the endpoint linked to our view set so what
this normally would do is list a set of objects that the view set represents
so let's create our list method by typing def list and you need to give it
the parameters self and the request object that is passed in by Django when
the request is made
Then we'll add a doc string that says return a hello message
and then what we'll do is just like we did for the get request in our API view
where we created a list of features that the API view has we're going to create
the same list for the view set so we'll type a view set equals create a list and
we'll write the first item of the list that says uses actions list create
retrieve update partial updates
and that's the first item of the list the
second item will be automatically maps to URLs using routers
and then the final item will be provides more functionality with less code so
these are three typical features of a view set and now what we'll do is we'll
return this object by doing return response and we'll give it a message
with hello and then we'll return a view set and assign this new a view set list
okay so when the request is made to our view set to the root URL
of the view set it will call this list function which will create this list
object here and then it will return it in a response in our API so make sure
you save that file and then we'll move on to the next video where we will
configure a URL to point to our view set.