Djangorestframework“AttributeError:“function”对象没有“get_extra_actions”属性

2024-10-02 02:40:49 发布

您现在位置:Python中文网/ 问答频道 /正文

django==3.2.4 djangorestframework==3.12.4

blog/serializer.py

from rest_framework import serializers
from .models import Blog

class BlogSerializer(serializers.ModelSerializer):
    class Meta:
        model = Blog
        fields = '__all__'

blog/views.py

from rest_framework import generics
from .models import Blog
from .serializers import BlogSerializer

class BlogListCreateView(generics.ListCreateAPIView):
    queryset = Blog.objects.all()
    serializer_class = BlogSerializer

class BlogRetrieveUpdateDestroyView(generics.RetrieveUpdateDestroyAPIView):
    queryset = Blog.objects.all()
    serializer_class = BlogSerializer

blog/url.py

router = DefaultRouter()
router.register(r'blogs', BlogListCreateView.as_view(), basename="blogs")
router.register(r'action/<int:pk>', BlogRetrieveUpdateDestroyView.as_view(), basename="action")

urlpatterns = [
    path('', include(router.urls)),
]

当我使用路由器时,它显示AttributeError:“function”对象没有属性“get\u extra\u actions” 但当我使用普通的django URL路径时,它会成功运行

blog/url.py

urlpatterns = [
    path('blog/', BlogListCreateView.as_view(), name="blog"),
    path('blog/<int:pk>', BlogRetrieveUpdateDestroyView.as_view(), name="action"),
]

Tags: frompyimportviewasblogallclass
2条回答

从文件:

Because we're using ViewSet classes rather than View classes, we actually don't need to design the URL conf ourselves. The conventions for wiring up resources into views and urls can be handled automatically, using a Router class.

因此,不需要路径为'action/<int:pk>''action'就足够了

Routers用于来自Django的Viewsets,而不是generics视图。例如:

from rest_framework import routers

router = routers.SimpleRouter()
router.register(r'users', UserViewSet)
router.register(r'accounts', AccountViewSet)
urlpatterns = router.urls

Here's如何使用generics进行此操作

相关问题 更多 >

    热门问题