如何让django所有的urls都成为顶级的插件?Top level slug我的意思是所有urls都有唯一的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()然后我将在mane 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('/')我需要为谷歌,因为如果有一天我决定将/articles改为/blog,那么我将打破谷歌搜索数以百计的网址。
发布于 2016-12-10 02:58:19
你的想法近乎完美。只有我推荐的更改:
1)似乎不需要Link模型。您的slug可以是Article模型本身内部的CharField
class Article(models.Model):
title = models.CharField()
slug = models.CharField(max_length=255, unique=True)
body = models.TextField()2)评论属于文章。因此,Review应该有一个指向Article的ForeignKey,而不是指向这个不应该再存在的Link对象的ForeignKey
https://stackoverflow.com/questions/41067055
复制相似问题