Django rest_framework DefaultRouter() class 与普通 url

Django rest_framework DefaultRouter() class vs normal url

我在 Django 中使用 REST,我不明白经典 URL 和实例化 DefaultRouter() 注册 URL 由 ViewSet 提供。

我有一个模型:

class Article(models.Model):
    title = models.CharField()
    body = models.TextField()
    author = models.ForeignKey()

像这样序列化模型:

from blog.models import Article


class ArticleSerializer(serializers.ModelSerializer):
    class Meta:
        model = Article
        fields = ['title', 'body', 'author']

查看Class:

from blog.models import Article
from rest_framework import viewsets
from .serializers import ArticleSerializer


class ArticleViewSet(viewsets.ModelViewSet):
    serializer_class = ArticleSerializer
    queryset = Article.objects.all()


和URLS:


router = DefaultRouter()
router.register(r'articles', ArticleViewSet)

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

是否可以在 URLS.py 中使用经典 URL 而不是像这样为 ViewSet 实例化对象:

urlpatterns = [
    path('api/', 'views.someAPI'),
]

我只知道 ViewSet 中的 HTTP 方法将方法转换为检索、列表等... 问题是我们可以在这种情况下使用 traditional(Classic) URL 样式吗?

感谢您的帮助。

嗯,简而言之,作为一名 Django 开发人员,众所周知在某些情况下很难在 Django 中处理正常的 URL。我们时不时地对详细信息页面的 id 类型感到困惑,在某些情况下,它是字符串或整数及其正则表达式,等等。

例如:

urlpatterns = [
url(r'^(?P<content_type_name>[a-zA-z-_]+)$', views.content_type, name = 'content_type'),
]

# or

urlpatterns = [
    url(r'^(?P<content_type_name>comics|articles|videos)$', views.content_type, name='content_type'),
]

更不用说在几乎所有情况下都需要有两个网址,例如:

URL pattern: ^users/$ Name: 'user-list'
URL pattern: ^users/{pk}/$ Name: 'user-detail'

主要区别

但是,使用 DRF 路由器可以自动完成上面的示例:

# using routers -- myapp/urls.py
router.register(r"store", StoreViewSet, basename="store")

django 如何理解它:

^store/$ [name='store-list']
^store\.(?P<format>[a-z0-9]+)/?$ [name='store-list']
^store/(?P<pk>[^/.]+)/$ [name='store-detail']
^store/(?P<pk>[^/.]+)\.(?P<format>[a-z0-9]+)/?$ [name='store-detail']

看看您仅用一行代码就节省了多少工作和头痛?

相比之下,根据 DRF 文档,routers 是一种使声明 url 变得容易的标准。来自 ruby-on-rails.

的模式

这是文档的详细信息:

Resource routing allows you to quickly declare all of the common routes for a given resourceful controller. Instead of declaring separate routes for your index... a resourceful route declares them in a single line of code.

— Ruby on Rails Documentation

Django 休息框架文档:

Some Web frameworks such as Rails provide functionality for automatically determining how the URLs for an application should be mapped to the logic that deals with handling incoming requests.

REST framework adds support for automatic URL routing to Django, and provides you with a simple, quick and consistent way of wiring your view logic to a set of URLs.

For more details follow the django rest framework documentation.