Django REST framework 关于类视图quretset和serializer的命名小坑

没有好好的读DRF文档,导致固定命名的的没有去固定命名,出现了个坑!
针对类视图中,查询集和序列化反序列化命名是固定的

1.首先来看下如果没有按命名规则去接收会报一个urls缺少base_name参数的错误。
这里我少写一个t
错误内容:

AssertionError: `base_name` argument not specified, and could not automatically determine the name from the viewset, as it does not have a `.queryset` attribute.

2, 因此我在urls中添加base_name:

from django.conf.urls import url

from restframework import views

#导入默认路由
from rest_framework.routers import DefaultRouter

urlpatterns = []
routers = DefaultRouter()
routers.register(r'books',views.BookInfoDRF,base_name='')#此处增加base_name
urlpatterns += routers.urls

3.运行,发现是可以成功的!

System check identified no issues (0 silenced).
July 01, 2018 - 14:18:04
Django version 1.11.6, using settings 'tangbao.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.

很开心,是不是解决了呢?当然不是,不然我为什么会一开始说要说命名固定写法??

4.前端进入,嗯,发现好像真的可以诶!
好像可以!!但是这不是目标地址,点击链接books试试

5.点击!!咦??

AssertionError at /restframework/books/
'BookInfoDRF' should either include a `queryset` attribute, or override the `get_queryset()` method.

6, 还是老老实实按规定蹦跶吧!!!

class BookInfoDRF(ModelViewSet):
    queryset= BookInfo.objects.all()
    serializer_class = BookInfoSerializer

7, 刷新!!一下子将我内心刷亮了,要的就是这种感觉,永远不要出bug。。。。不出bug??作为程序猿你在逗我??
成功了!

8, 最后将urls中的base_name去除也是ok的!


最后转载请注明出处!!谢谢!

猜你喜欢

转载自blog.csdn.net/lanxuezai/article/details/80874117