Views in Django
DRF includes a set of generic views that can be used to build CRUD (Create, Retrieve, Update, Delete) APIs for Django models. Here's an example view for a Book model:
python
from rest_framework import generics
from .models import Book
from .serializers import BookSerializer
class BookList(generics.ListCreateAPIView):
queryset = Book.objects.all()
serializer_class = BookSerializer
class BookDetail(generics.RetrieveUpdateDestroyAPIView):
queryset = Book.objects.all()
serializer_class = BookSerializer
In this example, we define two views: BookList and BookDetail. BookList is a view that lists all books and allows creating new ones. BookDetail is a view that retrieves, updates, or deletes a single book.
We specify the queryset (i.e., the set of objects to be used) and serializer for each view.
We can add these views to our app's urls.py file:
python
from django.urls import path
from .views import BookList, BookDetail
urlpatterns = [
path('books/', BookList.as_view(), name='book-list'),
path('books/<int:pk>/', BookDetail.as_view(), name='book-detail'),
]
This sets up two URL patterns: /books/ for the BookList view and /books/<id>/ for the BookDetail view.
No comments:
Post a Comment