Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AssertionError at /posts/ 'PostList' should either include a `queryset` attribute, or override the `get_queryset()` method

ERROR in url==http://127.0.0.1:8000/posts/
 D:\Priyanka_Angular1\virtual_env\django-angular\lib\site-packages\rest_framework\views.py in dispatch

                response = self.handle_exception(exc)

     ...

▶ Local vars
D:\Priyanka_Angular1\virtual_env\django-angular\lib\site-packages\rest_framework\views.py in handle_exception

                self.raise_uncaught_exception(exc)

     ...

▶ Local vars
D:\Priyanka_Angular1\virtual_env\django-angular\lib\site-packages\rest_framework\views.py in dispatch

                response = handler(request, *args, **kwargs)

     ...

▶ Local vars
D:\Priyanka_Angular1\virtual_env\django-angular\lib\site-packages\rest_framework\generics.py in get

            return self.list(request, *args, **kwargs)

     ...

▶ Local vars
D:\Priyanka_Angular1\virtual_env\django-angular\lib\site-packages\rest_framework\mixins.py in list

            queryset = self.filter_queryset(self.get_queryset())

     ...

▶ Local vars
D:\Priyanka_Angular1\virtual_env\django-angular\lib\site-packages\rest_framework\generics.py in get_queryset

                % self.__class__.__name__

serializer.py

from rest_framework import serializers
from posts.models import Post

class PostSerializer(serializers.HyperlinkedModelSerializer):
    author = serializers.Field(source='author.username')
    api_url = serializers.SerializerMethodField('get_api_url')
 
    class Meta:
        model = Post
        fields = ('id', 'title', 'description', 'created_on', 'author', 'url', 'api_url')
        read_only_fields = ('id', 'created_on')
 
    def get_api_url(self, obj):
         return "#/post/%s" % obj.id

views.py

from django.shortcuts import render
from rest_framework import generics
from posts.models import Post
from posts.serializers import PostSerializer
 
class PostList(generics.ListCreateAPIView):
  """
   List all boards, or create a new board.
  """
  model = Post
  serializer_class = PostSerializer
 
 
class PostDetail(generics.RetrieveUpdateDestroyAPIView):
  """
   Retrieve, update or delete a board instance.
  """
  model = Post
  serializer_class = PostSerializer
like image 707
jyur Avatar asked Nov 21 '16 13:11

jyur


1 Answers

You need to include queryset = Post.objects.all() in your PostList view, as well as in PostDetail.

Every view needs a queryset defined to know what objects to look for. You define the view's queryset by using the queryset attribute (as I suggested) or returning a valid queryset from a get_queryset method.

By the way, you can get rid of the model attribute in your views as they aren't used. That's not the correct way to tell the view what objects to look for.

like image 74
lucasnadalutti Avatar answered Sep 28 '22 07:09

lucasnadalutti