create a djano view set in python

To create a Django ViewSet in Python, you need to perform the following steps:

  1. Import the required modules:
main.py
from rest_framework import viewsets
from .serializers import YourModelSerializer
from .models import YourModel
111 chars
4 lines
  1. Define a class for your ViewSet which inherits from viewsets.ModelViewSet:
main.py
class YourModelViewSet(viewsets.ModelViewSet):
    queryset = YourModel.objects.all()
    serializer_class = YourModelSerializer
129 chars
4 lines
  1. Add the necessary routing in your Django project's urls.py:
main.py
from django.urls import path, include
from rest_framework.routers import DefaultRouter

from .views import YourModelViewSet

router = DefaultRouter()
router.register(r'models', YourModelViewSet)

urlpatterns = [
    path('api/', include(router.urls)),
]
254 chars
12 lines

In the above code, YourModel represents your Django model and YourModelSerializer is a serializer class that you need to create, which specifies how the data will be serialized/deserialized.

Make sure to replace models with a suitable URL endpoint for your model.

This setup will provide the standard CRUD operations (create, retrieve, update, delete) for your model, along with the appropriate routes.

related categories

gistlibby LogSnag