2010-07-19 74 views
0

我有兩個型號,蛞蝓領域:映射同一級的URL路徑不同車型

class Book(models.Model): 
    name = models.CharField(max_length=200) 
    slug = models.SlugField() 

class Author(models.Model): 
    name = models.CharField(max_length=200) 
    slug = models.SlugField() 

我想將它們映射到第一級路徑:

(r'^(?P<slug>[a-zA-Z0-9_-]+)/$', 'book_detail'), 
(r'^(?P<slug>[a-zA-Z0-9_-]+)/$', 'author_detail'), 

什麼在不使用相同函數的情況下完成此操作並返回基於slug的書籍或作者的最佳方法。

回答

4

,最好的辦法是將其在視圖中拆分:

r'^(?P<model>[a-zA-Z0-9_-]+)/(?P<slug>[a-zA-Z0-9_-]+)/$', 'some_detail') 

和看法:

def some_detail(request, model, slug): 
    try: 
     model = {'book':Book, 'author':Author}[model] 
    except KeyError: 
     raise Http404 

    item = get_object_or_404(model, slug=slug) 
    do_something_with(item) 
    ... 

編輯:哦,平這樣的...這將是:

(r'^(?P<slug>[a-zA-Z0-9_-]+)/$', 'universal_detail'), 

def universal_detail(request, slug): 
    try: 
     book = Book.objects.get(slug=slug) 
     return book_detail(request, book) 
    except Book.DoesNotExist: 
     pass 

    try: 
     author = Author.objects.get(slug=slug) 
     return author_details(request, author) 
    except Author.DoesNotExist: 
     raise Http404 

def book_detail(request, book): 
    # note that book is a book instance here 
    pass 
+0

謝謝。我想只有一個級別的網址。 mysite.com/mark-twain應該返回作者,mysite.com/a-dogs-tale應該返回該書。 – Boolean 2010-07-19 22:22:20

+0

很好,謝謝! – Boolean 2010-07-19 22:50:21