Is it possible to add 2nd slug to URL path in Djan

2019-07-24 20:12发布

I'm using Django version 2.1.

I want to create this type of URL Path in my Project: www.example.com/bachelor/germany/university-of-frankfurt/corporate-finance

Is it possible to do it in Django?

1条回答
来,给爷笑一个
2楼-- · 2019-07-24 20:44

Yes, say for example that you have a slug for an Author, and one for a Book, you can define it as:

# 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),
]

Then the view looks like:

# app/views.py

from django.http import HttpResponse

def book_details(request, author_slug, book_slug):
    # ...
    return HttpResponse()

The view thus takes two extra parameters author_slug (the slug for the author), and book_slug (the slug for the book).

If you thus query for /book/shakespeare/romeo-and-juliet, then author_slug will contains 'shakespeare', and book_slug will contain 'romeo-and-juliet'.

We can for example look up that specific book with:

def book_details(request, author_slug, book_slug):
    my_book = Book.objects.get(author__slug=author_slug, slug=book_slug)
    return HttpResponse()

Or in a DetailView, by overriding the 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']
        )

or for all views (including the DetailView), by overriding the get_queryset method:

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']
        )
查看更多
登录 后发表回答