Creating a Django REST framework (DRF) ViewSet involves defining a class that inherits from rest_framework.viewsets.ViewSet
or one of its subclasses, such as ModelViewSet
. Here's a step-by-step guide to creating a basic DRF ViewSet:
Install Django and Django REST framework: Make sure you have Django and Django REST framework installed. You can install them using pip:
bashpip install Django pip install djangorestframework
Create a Django project: If you haven't already, create a new Django project:
bashdjango-admin startproject myproject
cd myproject
Create a Django app: Create a new Django app within your project:
bashpython manage.py startapp myapp
Define a model:
In your models.py
file inside the myapp
directory, define a simple model:
python# myapp/models.py
from django.db import models
class MyModel(models.Model):
name = models.CharField(max_length=100)
description = models.TextField()
def __str__(self):
return self.name
Create a serializer:
In the serializers.py
file inside the myapp
directory, create a serializer for your model:
python# myapp/serializers.py
from rest_framework import serializers
from .models import MyModel
class MyModelSerializer(serializers.ModelSerializer):
class Meta:
model = MyModel
fields = '__all__'
Create a ViewSet:
In the views.py
file inside the myapp
directory, create a ViewSet for your model. You can use ModelViewSet
for basic CRUD operations:
python# myapp/views.py
from rest_framework import viewsets
from .models import MyModel
from .serializers import MyModelSerializer
class MyModelViewSet(viewsets.ModelViewSet):
queryset = MyModel.objects.all()
serializer_class = MyModelSerializer
Configure URLs:
In the urls.py
file inside the myapp
directory, configure the URLs for your ViewSet:
python# myapp/urls.py
from rest_framework.routers import DefaultRouter
from .views import MyModelViewSet
router = DefaultRouter()
router.register(r'mymodel', MyModelViewSet, basename='mymodel')
urlpatterns = router.urls
Include the app URLs in the project URLs:
In the urls.py
file of your project (inside the myproject
directory), include the URLs from your app:
python# myproject/urls.py
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('api/', include('myapp.urls')),
]
Run migrations: Apply migrations to create the necessary database tables:
bashpython manage.py makemigrations python manage.py migrate
Run the development server: Start the development server and test your API:
bashpython manage.py runserver
Visit http://127.0.0.1:8000/api/mymodel/
to interact with your API.
That's it! You've created a basic Django REST framework ViewSet with CRUD functionality. You can customize it further based on your specific requirements.