我有两个带有slug字段的模型:
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返回书籍或作者,最好的方法是什么。
答案 0 :(得分:3)
最好的方法是在视图中将其拆分:
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