AssertionError at / posts /' PostList'应该包含`queryset`属性,或者覆盖`get_queryset()`方法

时间:2016-11-21 13:36:12

标签: django-views

网址错误== http://127.0.0.1:8000/posts/  调度中的D:\ Priyanka_Angular1 \ virtual_env \ django-angular \ lib \ site-packages \ rest_framework \ views.py

            response = self.handle_exception(exc)

 ...

▶本地变量 handle_exception中的D:\ Priyanka_Angular1 \ virtual_env \ django-angular \ lib \ site-packages \ rest_framework \ views.py

            self.raise_uncaught_exception(exc)

 ...

▶本地变量 调度中的D:\ Priyanka_Angular1 \ virtual_env \ django-angular \ lib \ site-packages \ rest_framework \ views.py

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

 ...

▶本地变量 获取中的D:\ Priyanka_Angular1 \ virtual_env \ django-angular \ lib \ site-packages \ rest_framework \ generics.py

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

 ...

▶本地变量 D:\ Priyanka_Angular1 \ virtual_env \ django-angular \ lib \ site-packages \ rest_framework \ mixins.py in list

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

 ...

▶本地变量 get_queryset中的D:\ Priyanka_Angular1 \ virtual_env \ django-angular \ lib \ site-packages \ rest_framework \ generics.py

            % 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

2 个答案:

答案 0 :(得分:3)

您需要在queryset = Post.objects.all()视图以及PostList中添加PostDetail

每个视图都需要定义一个查询集来知道要查找的对象。您可以使用queryset属性(按照我的建议)或从get_queryset方法返回有效的查询集来定义视图的查询集。

顺便说一句,您可以删除视图中的model属性,因为它们未被使用。这不是告诉视图要查找的对象的正确方法。

答案 1 :(得分:0)

只需要包含在 views.py 中并创建 serializers.py

views.py 从autentication.serializers导入TestSerializer

authentication_classes = ()
permission_classes = ()
serializer_class = TestSerializer

serializers.py

from rest_framework import serializers
class TestSerializer(serializers.Serializer):

注意:具有djangorestframework 3.11.x的Python 3.8.x