简体   繁体   中英

Using Router vs including url in urlpatterns

Say I am creating a Todo app in Django, traditionally I would include a path to my app in the base_project urls.py file. However, today I came across a tutorial where they used a router for this same purpose I've already stated. Why would I want to use a Router instead of including the path in my urls.py file? For reference, here is a snip from the tutorial found at https://www.digitalocean.com/community/tutorials/build-a-to-do-application-using-django-and-react

 # backend/urls.py

from django.contrib import admin
from django.urls import path, include                 # add this
from rest_framework import routers                    # add this
from todo import views                            # add this

router = routers.DefaultRouter()                      # add this
router.register(r'todos', views.TodoView, 'todo')     # add this

urlpatterns = [
    path('admin/', admin.site.urls),         path('api/', include(router.urls))                # add this
]

Here backend is the main django project name.

Both works the same. You can add url in the urlpatterns. I had the same situation as yours where in a tutorial they were using routing instead of url patteren but i studied and both works the same.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM