I want to create a serializer without model.
myproject/myapp/views.py :
from rest_framework import viewsets
from rest_framework.response import Response
from .serializers import DemoSerializer
class DemoView(viewsets.ModelViewSet):
def get(self, request):
my_data = [{"name": "Harsha"}, {"name": "Harsha"}]
results = DemoSerializer(my_data, many=True).data
return Response(results)
myproject/myapp/urls.py
from django.urls import path, include
from . import views
from rest_framework import routers
router = routers.DefaultRouter()
router.register('demo', views.DemoView, basename='Demo')
urlpatterns = [
path('', include(router.urls)),
]
myproject/myapp/serializer.py
from rest_framework import serializers
class DemoSerializer(serializers.Serializer):
name = serializers.CharField()
When I goto URL: http://localhost:8000/demo/
, it is giving me following error:
DemoView should either include a queryset attribute, or override the get_queryset() method.
How can I resolve this error?
CodePudding user response:
from .models import Demo
class DemoView(viewsets.ModelViewSet):
def get_queryset(self):
return Demo.objects.all()
def get(self, request):
my_data = [{"name": "Harsha"}, {"name": "Harsha"}]
results = DemoSerializer(my_data, many=True).data
return Response(results)
If you don't want to create a model then you should extend viewsets.ViewSet
.
class DemoView(viewsets.ViewSet):
def get(self, request):
my_data = [{"name": "Harsha"}, {"name": "Harsha"}]
results = DemoSerializer(my_data, many=True).data
return Response(results)
CodePudding user response:
I think you need to customize list
method if you inherit from the ModelViewSet
.
class DemoView(viewsets.ModelViewSet):
queryset = Demo.objects.all()
def list(self, request):
my_data = [{"name": "Harsha"}, {"name": "Harsha"}]
results = DemoSerializer(my_data, many=True).data
return Response(results)