gpt4 book ai didi

python -/posts/ 'PostList'的AssertionError应该包含 `queryset`属性,或者重写 `get_queryset()`方法

转载 作者:行者123 更新时间:2023-12-03 17:05:14 24 4
gpt4 key购买 nike

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

最佳答案

您需要在queryset = Post.objects.all() View 以及PostList中包括PostDetail

每个 View 都需要定义一个查询集,以知道要查找的对象。您可以通过使用queryset属性(如我建议的那样)或从get_queryset方法返回有效的查询集来定义 View 的查询集。

顺便说一下,您可以在 View 中摆脱掉model属性,因为它们没有被使用。这不是告诉 View 要查找哪些对象的正确方法。

关于python -/posts/ 'PostList'的AssertionError应该包含 `queryset`属性,或者重写 `get_queryset()`方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40721512/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com