How to create a Django REST framework viewset



Image not found!!

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:

  1. Install Django and Django REST framework: Make sure you have Django and Django REST framework installed. You can install them using pip:

    bash
    pip install Django pip install djangorestframework
  2. Create a Django project: If you haven't already, create a new Django project:

    bash
    django-admin startproject myproject cd myproject
  3. Create a Django app: Create a new Django app within your project:

    bash
    python manage.py startapp myapp
  4. 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
  5. 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__'
  6. 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
  7. 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
  8. 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')), ]
  9. Run migrations: Apply migrations to create the necessary database tables:

    bash
    python manage.py makemigrations python manage.py migrate
  10. Run the development server: Start the development server and test your API:

    bash
    python 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.