2010-07-19 73 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