是否可以在Django的URL路径中添加第二个子弹?

时间:2018-09-09 15:48:55

标签: django python-3.x django-2.0 django-2.1

我正在使用Django 2.1版。

我想在我的项目中创建这种类型的URL路径: www.example.com/bachelor/germany/university-of-frankfurt/corporate-finance

是否可以在Django中实现?

1 个答案:

答案 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']
        )