我正在使用Django 2.1版。
我想在我的项目中创建这种类型的URL路径: www.example.com/bachelor/germany/university-of-frankfurt/corporate-finance
是否可以在Django中实现?
答案 0 :(得分:2)
是的,例如,假设您有一个Author
子弹,一个Book
子弹,您可以将其定义为:
# app/urls.py
from django.urls import path
from app.views import book_details
urlpatterns = [
path('book/<slug:author_slug>/<slug:book_slug>/', book_details),
]
然后视图如下:
# app/views.py
from django.http import HttpResponse
def book_details(request, author_slug, book_slug):
# ...
return HttpResponse()
该视图因此需要两个额外的参数author_slug
(作者的弹头)和book_slug
(本书的弹头)。
如果因此查询/book/shakespeare/romeo-and-juliet
,则author_slug
将包含'shakespeare'
,而book_slug
将包含'romeo-and-juliet'
。
例如,我们可以使用以下方法查找特定书籍:
def book_details(request, author_slug, book_slug):
my_book = Book.objects.get(author__slug=author_slug, slug=book_slug)
return HttpResponse()
或者在DetailView
中,通过覆盖get_object(..)
method [Django-doc]:
class BookDetailView(DetailView):
model = Book
def get_object(self, queryset=None):
super(BookDetailView, self).get_object(queryset=queryset)
return qs.get(
author__slug=self.kwargs['author_slug'],
slug=self.kwargs['book_slug']
)
或对于所有视图(包括DetailView
),通过覆盖get_queryset
方法:
class BookDetailView(DetailView):
model = Book
def get_queryset(self):
qs = super(BookDetailView, self).get_queryset()
return qs.filter(
author__slug=self.kwargs['author_slug'],
slug=self.kwargs['book_slug']
)