Let's talk about view sets at the beginning of the last section I
mentioned that the Django rest framework offers two classes that help us write
the logic for our API the API view and the view set
In the last section I
introduced you to the API view and in this section I'm going to teach you how
to use the view set.
So what are view sets? Just like API views, view sets allow
us to write the logic for our endpoints however instead of defining functions
which map to HTTP methods view sets accept functions that map to common API
object actions such as list for getting a list of objects
Create for creating
new objects retrieve for getting a specific object update for updating an
object partial update for updating part of an object and finally destroy for
deleting an object
Additionally view sets can take care a
lot of the common logic for us they're perfect for writing apis that perform
standard database operations and they're the fastest way to make an api which
interfaces with a database back-end
So when should you use view sets? Well a lot
of the time this comes down to personal preference however here are some
examples of cases when you might want to prefer a view set over an API view for
example if you need to write an API that performs a simple create read update and
delete operation on an existing database model
or you need a quick and simple API
to manage predefined objects or maybe you need a very basic custom logic
additional to the view set features already provided by the Django rest
framework
we'll learn more about that one in a bit finally you might want to
use a view set if your API is working with
standard database structure that's a basic overview of the view set don't
worry if you don't fully understand it at this point
sometimes you need to see an action for it to make sense so in the following
lessons in this section I'm going to walk you through creating a very basic
view set step by step