Skip to content

Commit

Permalink
Split serializers and views chapters
Browse files Browse the repository at this point in the history
  • Loading branch information
shabda committed Mar 13, 2018
1 parent 4b920c0 commit 6c07c8e
Show file tree
Hide file tree
Showing 3 changed files with 59 additions and 1 deletion.
3 changes: 2 additions & 1 deletion docs/index.rst
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,8 @@ Chapters:

setup-models-admin
apis-without-drf
chapter2
serailizers
views-and-generic-views
chapter3
chapter4

Expand Down
File renamed without changes.
57 changes: 57 additions & 0 deletions docs/views-and-generic-views.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@

Creating Views
----------------

Let us use generic views of Django Rest Framework for creating our views which will help us in code reusablity. The generic views alos aid us in building the API quickly and in mapping the database models.

.. code-block:: python
from rest_framework import generics
from .models import Poll, Choice
from .serializers import PollSerializer, ChoiceSerializer,\
VoteSerializer
class PollList(generics.ListCreateAPIView):
"""
List all polls, or create a new poll.
"""
queryset = Poll.objects.all()
serializer_class = PollSerializer
class PollDetail(generics.RetrieveDestroyAPIView):
"""
Create a Poll, delete a poll
"""
queryset = Poll.objects.all()
serializer_class = PollSerializer
class ChoiceDetail(generics.RetrieveUpdateAPIView):
"""
Retrieves a Choice, Updates a Choice
"""
queryset = Choice.objects.all()
serializer_class = ChoiceSerializer
class CreateVote(generics.CreateAPIView):
"""
Create a vote
"""
serializer_class = VoteSerializer
When writting a generic view we will override the view and set several calss attributes.

Let us have a look in to the important parts in the code.

- queryset: This will be used to return objects from the view.
- serializer_class: This will be used for validating and deserializing the input and for seraizling the output.

0 comments on commit 6c07c8e

Please sign in to comment.