【发布时间】:2016-12-09 18:52:29
【问题描述】:
如何使 django 的所有 url 成为顶级 slug? 顶级 slug 我的意思是所有 url 都有独特的 slug 示例:
example.com/articles
example.com/article-1
example.com/article-2
example.com/article-3
example.com/reviews
example.com/reviews-1
example.com/reviews-2
but not:
example.com/articles/article-1
example.com/articles/article-2
example.com/articles/article-3
example.com/reviews/reviews-1
example.com/reviews/reviews-2
我有很多应用,例如文章、评论和其他自定义页面。
那么,您对我使用这样的模型创建应用程序的这种方法有何看法:
class Link(models.Model):
slug = models.SlugField(unique=True)
然后我将在我的文章模型中使用它,如下所示:
from links.models import Link
class Article(models.Model):
title = models.CharField()
slug = models.OneToOneField(
Link,
on_delete=models.CASCADE,
primary_key=True,
)
body = models.TextField()
.
from links.models import Link
class Review(models.Model):
title = models.CharField()
slug = models.OneToOneField(
Link,
on_delete=models.CASCADE,
primary_key=True,
)
review = models.TextField()
然后我的鬃毛 urls.py 文件中将只有一个 url 字段:
url(r'^(?P<slug>[-_\w]+)', views.link, name='link'),
现在我应该如何过滤我想要返回文章或评论的数据?
这样还是有更好的解决方案?
from django.http import HttpResponseRedirect
from .models import Link
from articles.models import Article
from review.models import Review
def link(request, link):
link = Link.objects.get(link=link)
if Article.objects.filter(slug=Link).exists():
link = link.slug
return HttpResponseRedirect(link)
if Review.objects.filter(slug=Link).exists():
link = link.slug
return HttpResponseRedirect(link)
return HttpResponseRedirect('/')
Google 需要它,因为如果我决定有一天将 /articles 更改为 /blog,那么我将在 google 搜索中破坏数百个 url。
【问题讨论】: